#templates-archived
1 messages Β· Page 108 of 1
it seems like
{{ is_state('input_boolean.day' + d | string, 'on') }}
{{ states('input_boolean.day' + d | string) == 'on' }}
are the same number of characters π
perhaps preference, then π
not sure if widow9098 is here anymore, but it was a good exercise for me. thanks
i have a template sensor that returns a list. how can i reference that list in another template? ie how can i cast a string representation of a list into an actual list
perhaps i could parse the string as json.... doesn't seem to be possible...
What is the actual value?
"['2020-11-02T15:30:00.000Z', '2020-11-02T13:45:00.000Z', '2020-11-01T09:30:00', '2020-11-02T09:00:00']"
piping that into from_json gets JSONDecodeError: Expecting value: line 1 column 2 (char 1)
rofl ok if i string replace the single quotes into double quotes i can use from_json to deserialize the list
is there a less hacky way?
if i pipe the string into list i just get a list of each of the characters
yes, the list is the output of another template sensor and then two more template sensors parse that list in different waysa
Add a |tojson to the generator template
Hey guys,
trying to set an "input_number" to a value of a certian sensor. If I call the "input_number.set_value" service with the following data:
entity_id: input_number.tinte_schwarz
value: {{ states('sensor.canon_tr8500_series_black_bk') | float }}
I am getting this error message: "expected float for dictionary value @ data['value']". Any idea how to solve this?
you need to quote the template
and you won't be able to do that in the devtools, only in a script/automation
How do I get the area from a state trigger in automations?
@inner mesa Ah ok, then that's my fault. Tried it first in the dev tools
it should work there, and I filed an issue for it
@inner mesa Ah ok. Do I need a single " or "" to quote the template?
double (") in your case. just make sure that you use different quotes outside from what you use inside
I am using a template to combine multiple motion sensors into one. I then use NodeRed to turn lights off based upon the one sensor. My question is, why doesn't the template "reset" or start over again once the delay off has been satisfied? Snip it of code:
- platform: template
sensors:
motion_hall_bath:
friendly_name: "Hall Bath"
delay_off:
minutes: 3
entity_id: binary_sensor.wyzesense_77a64a20,binary_sensor.hall_bath
device_class: motion
value_template: >-
{{ is_state('binary_sensor.wyzesense_77a64a20', 'on')
or is_state('binary_sensor.hall_bath', 'on') }}
Need to add that the reset should occur due to the sensor triggering a timer in NodeRed prior to turning off the lights. I would think that if motion is detected prior to the timer expiring, it would start over again.
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
why would it "reset"? I'm not following what you're looking for
BTW, the entity_id: line should be removed. It's no longer supported
that template should turn on immediately when either of those sensors reports on, and wait for 3 minutes of evaluating "false" before turning off
After the 3 minutes and before my timer in NodeRed has expired, if motion is sensed again, I want the template to start timing again and turn to on.
The template isn't timing, the sensor is.
And it'll reset only when the template evaluates to 'off' for 3 full minutes.
Taking node red out of this, delay_off only starts when it evaluates false
So any motion detected within the 3 minutes on either of the sensors in your template will reset the 3 minute delay_off.
Sensors are all off, delay_off timer starts. At the end of the delay_off should any motion, assuming all of the sensors are still off, restart the template?
The template is evaluated every time either of the entities it references change state (or attributes, but you don't care about that).
The template doesn't have any notion of a timer. It doesn't 'restart'.
If motion should activate the template, I have another problem then.
Templates arenβt activated or restarted
I think I got it. I will look at what is happening during the state change. Thanks for the help.
at any given moment, they evaluate to something
hi. I'm looking for right syntax for strftime. I have date and i want to extract name of the day from the date. {{ state_attr('weather.home', 'forecast')[0].datetime }} is returning me 2020-11-03T11:00:00+00:00 is it possible to get a name of the day from this form. I tried : {{ {state_attr('weather.home', 'forecast')[0].datetime}.strftime("%a") }} , {{ (state_attr('weather.home', 'forecast')[0].date).timestrftime("%a") }} , but this is not working. Is my syntax wrong, or the format of date is wrong
oh. found the solution
{{ as_timestamp(state_attr('weather.home', 'forecast')[0].datetime) | timestamp_custom('%A', False) }}
{{state_attr('weather.home', 'forecast')[0].datetime | as_timestamp | timestamp_custom("%A", false)}} works too if you prefer that format.
Now I want to create for loop to create multiple sensors, so i don't have to configure them one by one. I put this together, but i have a feeling that, this won't do the trick. So i want to create sensors day_0, day_1, day_2, day_3
I have to define every sensor in config then, no soulution via for loop?
Not built-in. You could use an external preprocessor for the config file, but what's saved would be the same as if you did it yourself.
ok, notepad++ it is then:)
Hi all, anyone available to help out? I'm completely stuck with the new templating-stuff.
It's probably something silly...
Just ask your question, and if someone can answer they will.
@austere isle posted a code wall, it is moved here --> https://paste.ubuntu.com/p/S5bpWBJwMb/
@austere isle posted a code wall, it is moved here --> https://paste.ubuntu.com/p/4D34THfc5F/
sigh HassBot is removing my code
I'm currently using this: {% if states('sensor.time') <= "10:30" %}
To check if it's before 10.30 obviously.
This however gives an error now.
Error executing script. Invalid data for call_service at pos 1: template value should be a string for dictionary value @ data['attributes_template']
It does that to stop too long messages from filling up the chat
I don't think you can template a whole block of attributes like that.
Let me try to put the whole thing in here in parts so that Hassbot won't bug me π
- service: variable.set_variable
data:
variable: verlichting_woonkamereethoek_waarden
value: true
attributes_template: >
{
{% if states('sensor.time') <= "08:30" %}
"doelhelderheid": "80",
"doelkleurtemperatuur": "400"
{% else %}
"doelhelderheid": "40",
"doelkleurtemperatuur": "400"
{% endif %}
}
This used to work.
When I user legacy_templates: true it still does
Try yaml attributes_template: doelhelderheid: "{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}" doelkleurtemperatuur: 400
Looking at https://github.com/rogro82/hass-variables, the attributes_template should return a json object, therefore the correct synthax would be
attributes_template:
{
"doelhelderheid": "{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}",
"doelkleurtemperatuur": 400
}
I think it has to do with the sensor.time thing. (it is explicitly mentioned release notes of 0.117)
Same error
Invalid data for call_service at pos 1: template value should be a string for dictionary value @ data['attributes_template']
what does return {% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%} when you evaluate it in the template tool ?
in my code I forgot the > :
attributes_template: >
{
"doelhelderheid": "{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}",
"doelkleurtemperatuur": 400
}
same error?
Yup
Just to confirm. Would it have to do with: https://www.home-assistant.io/blog/2020/10/28/release-117/#breaking-changes
Templates - Auto-updating now()
don't think so
π
As I said. My original code works fine if I use the 'legacy templating'
Any other ideas?
Did you look at this ? https://github.com/rogro82/hass-variables/issues/47 didn't go in the detail, but it is your error message, and linked to the 0.117
they use attributes instead of attributes_template, but I don't know with which version
attributes_template:
doelhelderheid: "{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}"
doelkleurtemperatuur: 400
https://github.com/rogro82/hass-variables/issues/47#issuecomment-717178320
so to conclude and for reference:
using Ha pre 117: don't change the CC and use attributes_template: in the service-call, and use legacy_templates: true
using HA 117.+: change the CC as Frenck suggests here and change to use attributes: in the service-call
Yup. That is it.... Thanks loads! π
I don't think I would have thought on looking at the Variables addon. (especially with the remarks in the changelog about the now() ).
@austere isle are you sure this works?
{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}
It's 12:08 here (and based on your attribute names I guess it's the same for you) and the template below gives 40 in the checker, I would expect 80 then
{% if states('sensor.time') <= '14:30' %}80{% else %}40{%endif%}
Oh, nevermind, I guess I don't have sensor.time enabled. {{ states('sensor.time') }} gives status unknown for me
Yes it works fine:
{% if states('sensor.time') <= '14:30' %}80{% else %}40{%endif%} ## >> 80
{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%} ## >> 40
(( I may have copy-pasted it incorrectly ))
I'm using the code for about half a year now. But since 0.117 it failed with the new template-engine
but slashback pointed me to the right direction π
you could also use
{{ 80 if states('sensor.time') <= '08:30' else 40 }}```
ey @silent barn, I've corrected it!
True. But the original code has more times and loads of items using that. So for readability, my original code looks like:
value: true
attributes: >
{
{% if states('sensor.time') <= "08:30" %}
"doelhelderheid": {{ "80" | int }},
"doelkleurtemperatuur": {{ "400" | int }}
{% else %}
"doelhelderheid": {{ "40"| int }},
"doelkleurtemperatuur": {{ "400"|int }}
{% endif %}
}
service: variable.set_variable
(pff don't look at the spaces. copy-paste error)
Anyway.. Thanks again all π
hmm, now that templates will return native types could probably simplify
attributes: >
{% states('sensor.time') <= "08:30" %}
{{ {
"doelhelderheid": 80,
"doelkleurtemperatuur": 400
} }}
{% else %}
{{ {
"doelhelderheid": 40,
"doelkleurtemperatuur": 400
} }}
{% endif %}
is it possible to create a template sensor that returns the current logged in user? I was using custom header for this with the following code but when I try this as a temple it does not return the Username:
{%- if now().hour < 12 -%}Good Morning {{user}}!{%- elif now().hour < 18 -%}Good Afternoon {{user}}!{%- else -%}Good Evening {{user}}!{%- endif -%}
For some reason this code is not loading, but works fine in the developer tools/templates... any suggestions?
sensors:
marco_in_gti:
friendly_name: "Marco in GTI"
value_template: "{% if '48:F0:7B:2C:7F:4A' in state_attr('sensor.marco_cell_bluetooth_connection', 'connected_paired_devices') %}true{% else %}false{% endif %}"```
@worn lintel no. Unless the front end templating enviro is configured differently, the standard template environment doesn't have access to that info
probably better for #frontend-archived
"{{ '48:F0:7B:2C:7F:4A' in state_attr('sensor.marco_cell_bluetooth_connection', 'connected_paired_devices') }}"
Thanks for that, had been messing with it for hours...
the in test already returns true/false. no need to wrap it
hello, how can I check if some sensor triggered in some specific timeframe? For example I have a tag at the door, and I have xiomi motion sensor outside of the door.
scenario: user with phone scan tag, but condition is if movement sensor last triggered 15 seconds ago
if not, that means that user is planning to leave the house
if last triggered motion sensor is triggered in that specific time frame (less then 15 seconds), that means that users is entering into the house
so tag reading would have 2 automations: left_house and welcome_house based on that last triggered sensor
This sounds like an automation
yes but I need just a template for service_template part
do I use something like this {{ now().timestamp() - as_timestamp(states.DOMAIN.OBJECT_ID.last_changed) > 20*60 }}
Sure
now().timestamp ?
I wanted just to check in some of the last version of HA bunch of things are changed, added new timers etc
maybe is there a cleaner way Idk
If you want to check that it's been at least 15 seconds since something triggered, comparing the current time to the last_changed value is the best way.
Alternatively, you could have a timer that restarts every time there's motion detected. If the timer has run down, that means there's been no motion.
If you want to avoid templates, that's probably the next best option.
{{as_timestamp(states('sensor.frontdoor_last_movement_time'))}} Im getting the result None
{{states('sensor.frontdoor_last_movement_time')}} => Monday 02-Nov-20, 20:23:07
What's the config for that sensor?
If that sensor is just giving a string, you might have to use strptime. I don't know Python well enough to know when as_timestamp works and when strptime is needed.
I'm guessing that the former needs a datetime object to operate on.
well, Im having just a date in this format
{{ ( as_timestamp(now()) - as_timestamp(state_attr('sensor.frontdoor_last_movement_time', 'last_triggered')) |int(0) ) < 15 }}
I found something like this
but its always false π
timedelta is a thing
you are searching for last_triggered on a sensor
It doesn't exist. last_triggered is for automation
if your are looking for the last change of the sensor, you should use states.sensor.frontdoor_last_movement_time.last_changed
Can someone help me to figure out how to make this better and/or make it work at all? It kinda works but not really. This is what I have below but I get the following error from the template tools: TypeError: '>' not supported between instances of 'str' and 'int'
{% if now().strftime("%B") == "October" %}
HALLOWEEN
{% elif now().strftime("%B") == "November" and now().strftime("%-d") > 27 %}
CHRISTMAS
{% elif now().strftime("%B") == "December" %}
CHRISTMAS
{% else %}
NONE
{% endif %}
...time("%-d")|int > 27 ...
@dreamy sinew You rock!!! That was easy π
Value template on a cover (https://www.home-assistant.io/integrations/cover.template/)
I have a door sensor that evaluates to on/off. Do I need to run that through another template sensor to make it open/closed before it is usable with the cover?
I'd say you just need to put something like {{ is_state("sensor.your_door_sensor", "on") }} in the value_template (if your door sensor is on when the door is open)
OK. Something that evaluates to true when it is open...
yes
Morning Team! I am trying to create a 'fake switch' that will allow me to expose it to homekit and turn on / off when i am home / away. This will essentially become my presence detector. How do i create a 'fake switch' that turns on / off but not send any data. I attempted it . but not sure this is right?
- platform: template
switches:
homekit_presence:
friendly_name: Away Mode
turn_on:
service: switch.turn_on
turn_off:
service: switch.turn_off```
why not just use a input_boolean: ?
Indeed input_boolean seem to be exposed in homekit and are treated as switch : https://www.home-assistant.io/integrations/homekit/#supported-components
ahh okay cool - thank you! That works perfectly
Hi, i'm trying to make a notification group that will send notification to the person who is at home. If none of us are at home, it should send it to us both.
In my notifications.yaml i have the following:
- name: athome
platform: group
services:
- service: "{% if states('input_boolean.person_2_home') == 'on' and states('input_boolean.person_1_home') == 'on' or states('input_boolean.person_2_home') == 'off' and states('input_boolean.person_1_home') == 'off' %}all{% elif states('input_boolean.person_1_home') == 'on' %}sander{% elif states('input_boolean.person_2_home') == 'on' %}kirsten{% endif %}"
but when i run an config check, i get an Invalid config for [notify.group]: invalid slug, is there anyway to use template stuff here?
I donβt know that you can use a template there
You may need to put that logic in a script instead. It would be pretty similar with a choose: block
No, choose: is a way to do an if/then/else construct in a script
You canβt do what you want in a notify group be sure itβs trying to construct a notify service out of your template without evaluating it
Strange it should be supported?
I suspect that thatβs an exception
Itβs a different use case than the typical service template
Ghehehe
a few months ago I created a sensor template so I can see in lovelace how long ago a automation was run ( device_class: timestamp; value_template: '{{ states.automation.muffin_essen_start.attributes.last_triggered }}' ). Is there now a cleaner solution?
@inner mesa Got it almost working, only the actions don't show up:
- service: "notify.{if here}"
data:
title: "{{title}}"
message: "{{message}}"
data:
image: "{{data.image}}"
actions: >
{% for action in data.actions %}
- action: {{ action.action }}
title: {{ action.title }}
{% endfor %}
Image does work, just need to pass the array in data.actions to the service
Templates can only be used for values, not for keys.
So it's not possible?
That's what I just said
hmm, couldn't you output a full dict if you constructed it properly with the new typing?
Hmm, maybe. I wouldn't like to try π
I thought the main problem would be that the integration itself needs to know which fields to validate and then which fields can accept templates.
i think anything under the top level data key could be templatized
But does the validation of the structure occur before or after the evaluation of the templates?
If it's before, you're missing most of the structure still.
should be easy enough to test
actions: >
{{ [{"action": "action", "title": "title"}] }}
Makes sense. @viral latch, try that (without your loop for now)
if that works i have an idea for the loop
actions: >
{%- set ns = namespace(actions = []) -%}
{%- for action in data.actions -%}
{%- set ns.actions = ns.actions + [{"action": action.action, "title": action.title}] -%}
{%- endfor -%}
{{ ns.actions }}
This stuff makes me grateful to be a JS dev, not a Python dev. Concatenating arrays like that feels dirty π
Ah
l = list()
l.append("foo")
l.append("bar")
l.extend(["blah", "mono"])
-> ['foo', 'bar', 'blah', 'mono']
Yeah, that syntax is fine. It's the + that upsets me π
I'm used to Array.push() in JS.
apparently jinja supports that too but the env that is enabled in HA restricts that out
I wonder if you can unpack them too or if the env blocks that.
unpack how?
set ns.actions = [ *ns.actions, {"action": action.action, "title": action.title}]
If I've understood the syntax correctly.
i'm not aware of that syntax
you can do this in python but not in jinja
[{"key1": x['a'], "key2": x["b"]} for x in l]
[{'key1': 'foo', 'key2': 'bar'}, {'key1': 'bar', 'key2': 'foo'}]```
That's neat
"list comprehension"
coming from C, list comprehensions blow my mind.
they're at once both awesome and terrifying
lol they're kinda dangerous if you're not careful
Not sure if this is the right channel. I'm trying to figure out how to convert an analog value from soil moisture sensor to human readable percentage. Is template the right place to do it?
Okay so if I want to create a percentage value for sensor.tasmota_analog_a0 entity, would this be the right approach?
sensor:
- platform: template
sensors:
plant_soil1:
friendly_name: Schefflera
unit_of_measurement: percentage
value_template: '(100 - ((states.sensor.tasmota_analog_a0.state_with_unit|int - 456) * 100) / (846 - 456))|round'
needs to be a valid template
value_template: "{{ (100 - ((states('sensor.tasmota_analog_a0')|int - 456) * 100) / (846 - 456))|round }}"
if you want to start diving deep on templates it might behoove you to go have a look at the jinja2 docs
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
I've done jinja2 in the past, thanks tho!
even with past experience, there are extensions and best practices that are specific to HA: https://www.home-assistant.io/docs/configuration/templating/
states('xxx') vs. states.xxx.state, for isntance
yeah, i flipped that and didn't explain it
states.xxx.state throws an exception if it's unavailable, states('xxx') does not
How can I add a leading zero if the value < 10?
{{ (states('input_number.oprit_last_motion_event') | int) }}
If the value is > 10 or <10 ? makes more sens if < 10 no ? If < 10 try this {{ "%02d" % (states('input_number.oprit_last_motion_event') | int) }}
@deft timber indeed, less then < 10
Hi, i would like to create a template sensor that holds the average temperature. I thought of using https://www.home-assistant.io/integrations/min_max but next to entities, i also have some temperatures as an attribute on an entity. How can i point to those in the entity_ids list | string ?
of course i can use value_template: >- {{ ((float(states('sensor.flora01_temperature')) + float(states('sensor.flora02_temperature')) + float(states('sensor.hallway_pir01_temperature_air')) + float(states('sensor.livingroom_pir02_temperature_air')) + float(state_attr('climate.kitchen_thermostat01_thermostat', 'current_temperature') + float(state_attr('climate.livingroom_thermostat02_thermostat', 'current_temperature') ) / 6) | round(1) }} but would be nice i dont have put that hard coded 6 there.
Hey everyone! I'm looking for someone who's good with math, 'cause my head hurts thinking about this:
I'm looking for a template that calculates a value based on the sun.suns' azimuth attribute. First going up, and then going down again. So when the azimuth is 90; the value should be 1, when it's 180; the value should be 100, and when it's 270; the value should be back at 1.
I want to use this to set the starting brightness_pct (and color_temp) when I turn on a lamp.
It's maybe a lot to ask for this formula, but if there's any math geniuses here that find this easy or fun (or both), feel free to give it a shot!
Thanks!
I found this on StackOverflow, but it's not quite right as it just keeps getting brighter up until azimuth 270:
brightnessPct = (((azimuthCurrent - azimuthMin = 90) * (brightnessPctMax = 100 - brightnessPctMin = 1)) / (azimuthMax = 270 - azimuthMin = 90)) + brightnessPctMin
If possible, it should peak at azimuth 180 and start going down again.
@nocturne sleet in excell i come to this formula =100-ABS(((A1-90)/90*100)-100)
but with 0 instead of 1 at the extremities
in excel too I got it with =MAX(-(COS(azimutCurrent/180*PI())*99-1);0)
I'm using a cosinus to have a smoother formula, not a linear one
and it returns 0 if azimut is below 90 or above 270
In a template, my version gives {{ -(((azimutCurrent / 180 * pi)| cos) * 99 - 1) | max(0) }}
Wow! That's great!!
Could it be tweaked so that it returns 1 instead of 0 when azimuth <= 90 or azimuth >= 270
replace max(0) with max(1)
Hi huys. I'm new to home assistant.
I'm trying to configure a custom rest notify service, where I want to send to state of all person in my config into the data_template field.
I can do it adding lines manually, but I would like to extract all users (some kind of for loop) .
Is this something possible?
yes you can loop on the person
{% for p in states.person -%}
{{p.entity_id}}: {{p.state}}
{%endfor%}
@deft timber Sorry to bother again, but could the function be tweaked to do the same thing with color temperature? In Kelvin?
At azimuth 90 and 270 the colorTempKelvin == 2200 and at azimuth 180 (peak) the colorTempKelvin == 4000.
I tried tweaking the values in the formula, but could only get it working correctly with numbers sub 100
I'm busy right now, I can watch that in 2h
=2200+MAX(-(COS(A3/180*PI())*(4000-2200));0)
thanks @deft timber but I'm not sure I get how I can do that in a data_template field
it's an object in yaml
data: >
{% for p in states.person -%}
{{p.entity_id}}: {{p.state}}
{%endfor%}
How can I add 5 min offset to this template?
'''
{{
as_timestamp(states('sensor.redmi_note_7_next_alarm')) |
timestamp_custom('%H:%M')
}}
'''
+ timedelta(mins=5) I think
+ timedelta(mins=5)I think
@inner mesa TypeError: 'mins' is an invalid keyword argument for new()
π«
looks like it's "minutes"
it's also in the docs
{{ now() + timedelta(minutes=5) }}
well it returens a string.. what am i missing?
TypeError: can only concatenate str (not "datetime.timedelta") to str
I want to implement a loop until an other automation is started by a webhook, how can I manage that? What template should I use?
@small rock Sorry, I think you'll need to create an input_boolean to indicate that the webhook triggered and use that as the condition in a repeat: block
I keep forgetting that we have no break-like statement to get out of a loop
UndefinedError: 'datetime.timedelta object' has no attribute 'strftime'``` {{ (now() + timedelta(minutes=5)).strftime('%H:%M') }}
@dreamy sinew I am getting there but can't combine it with the sensor :/
@native pilot the alternative is to just to add 5mins (5 * 60) to the timestamp
show what you are actually doing then
decide whether you want to work with datetime or timestamp and do the right thing
Do you mind explaining the diff like I'm a five year old.?
I have basic knowledge in python but some things I just can get right
I have a camera (motioneye) sends a webhook and want to do image_processing until the webhook motion ended
For each webhook I have an automation
datetime is an object and timestamp is a number representing the number of seconds since Jan 1 1970
both are perfectly valid ways to represent the same info
so if i am getting the sensor value as a timestamp like I have now - the reasonable choice will be to add a seconds like your example above?
@small rock then you can use input_select to represent which automation fired, or a series of input_boolean
sure, you can do that. +300
I just immediately jumped to timedelta, which was probably not the best option for you
you can try this all in
-> Templates to see what each part is spitting out and make sure you get the result you want
@inner mesa Thanks!! figured it finally.. took some time to get it right (int and str and the formatting in general are pain)
Life saver
np, I hate time/date stuff and usually have to play around with it until I get it right
I hate anything time/date related with templating
yeah, because every sensor is returning a string, then you have to convert it to a time object to get the numbers, then to int to manipulate, and to time object again - and at the end it is always a string
@ robc I was thinking something like this:
{{ as_timestamp(states.automation.motioneye_oprit_webhook_off.attributes.last_triggered) - as_timestamp(states.automation.motioneye_oprit_webhook_off.attributes.last_triggered) | int > 0 }}
does it work?
you should use state_attr('automation.motioneye_oprit_webhook_off', 'last_triggered')
aren't you subtracting the same thing from itself?
you want webhook_on or something?
{{ as_timestamp(state_attr('automation.motioneye_oprit_webhook_off','last_triggered')) - as_timestamp(state_attr('automation.motioneye_oprit_webhook_on','last_triggered')) | int > 0 }}
@inner mesa I have done it like this:
{{ (as_timestamp(state_attr('automation.motioneye_oprit_webhook_off','last_triggered')) - as_timestamp(state_attr('automation.motioneye_oprit_webhook_on','last_triggered')) | int > 0) or is_state('binary_sensor.oprit_motion','on') }}
Is there a way to use secret in templates?
yes, at least you can put your whole template in to a secret
a little backwards, but it works fine
(I haven't read your whole conversation, just answering "Is there a way to use secret in templates?")
@waxen rune also in automation or secrets? Or do I need to make a sensor out of it?
hmm.. probably a sensor. I haven't read what you actually try to fix, I just read the last line π
It's just that one line
I just fixed what I wanted and it was more like a additional question
ok. if you want to create a sensor that's using a parameter you don't want visible, you can put the whole sensor in secrets, I have an example in link link above. just tried it the other day
I don't know if that's a good way, but it worked fine when I tried it.
Thanks I'll check it out later
can someone help me with a syntax problem?
@hollow obsidian Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
ok! I build an entity scraped from web with - platform: scrape and it works (called entity.first), then I build another one (called entity.second) and this is ok. Now i want to build another entity (called entity.diff) that is the different among the two. What is the way to build entity.diff? What sintax?
@hollow obsidian Generally, it no harder than the math you need for your operation. Can you share your config? Otherwise it's hard to help.
yes, let me try
- platform: scrape
name: press bz
resource: http://meteo.provincia.bz.it/stazioni-meteo-valle.asp?stat_stid=1242
select: "div#content:nth-child(4) > section > div.lv_grid_container > div.weather_box_lightest:nth-child(2) > div.station-data.row:nth-child(2) > div.station_sensor_values.col-sm-8:nth-child(2) > ul.station-values:nth-child(2) > li:nth-child(4) > strong"
an this build entity.press_bz
the other is:
- platform: scrape
name: Max VENTO
resource: https://meteopassione.com/stazioni/toscolano
select: "#col-dati.col.col-12.col-sm-3.col-md-3.col-lg-3.col-xl-3:nth-child(6) > div#box-dati > div.col.col-xs-12.col-sm-12:nth-child(3) > div.row.sfondo-stazione.bg-5 > div.col.col-xs-12.col-sm-5.footer:nth-child(1) > p:nth-child(1)"
and the states (values) of those?
an this build the second called entity.max_vento
ok, to extract the value I use this: (wait 1 sec I need to rewrite)
- platform: template
sensors:
pressione_bz:
value_template: "{{ states('sensor.press_bz') | string() | trim() | truncate(4,true,'') | round(2) | float()}}"
ok, does that work as expected? what is the state right now for example?
this give back a number, for example now it's 1027.0
but now I want to subtract another variable and give the result to another entity
it's only a sintax error my mistake
ok, that should be fine. this is an example a template sensor that calculates (x + y) / 2 :
like value_template: "{{ (((states('sensor.pressione_bz')|float|round(1)) - (states('sensor.max_vento_nodi') |float|round(1))) /2) | round (1)}}"
The other entity is this:
- platform: template
sensors:
max_vento_nodi:
friendly_name: "MAX vento in nodi"
unit_of_measurement: "kn"
value_template: "{{ states('sensor.max_vento') | string() | trim() | truncate(3,true,'') | float()/1.8 | round() }}"
It can be made simpler, I just copied that as an example
yesssssss
does that answer your question?
1 second I need to understand
((states('sensor.pressione_bz')|float|round(1))
is the first argument
yep, the state, made to a float number and rounded of to one decimal
so after the {{ i can use the ( as typical sintax
ok perfect I will try
another , please π
...
is "TRUNCATE" the best way to get data from a serie?
(i think ther is a better way)
I find doc here: https://jinja.palletsprojects.com/en/master/templates/
let me explain better: I scrape a data from a website, it give back an entity that seems like "10.4","km/h","EWE","17.5","Β°C","","","Italy"
so I need to extract the 4Β° data, 17.5, the temperature
what is the right command to get the 4th data?
Does it return an array ([a,b,c])?
From that example, I'd guess you could go for a json template.
yes it seems an array
For arrays, you can use [index] to get something back from that position. So if you have an array called list, list[1] gets the second item back from that array (it counts from 0).
Hi what is the best way to update the status of a switch without actually doing a service call?
Walk up to the switch and press it π
well I got three buttons, fan speed, i just want each time i press a one button, other two get reset to default.
Are you talking about Lovelace?
buttons are on lovelace, but can status be modified through switch templates?
If you have 3 'radio buttons' on your Lovelace and only one should ever be active, you have a couple of options. How you do it depends on what those buttons represent.
What are they for? What do they do when they're pressed?
okie may be the way I implement is incorrect, at the moment, i got three buttons as lovelace button card, so each button press, it send a RF call via broadlink, so just as old school fan switch, each time one speed is pressed, i just want other one to be off state, without sending a command. Maybe my method of attack to this issue is not so good π¦
So... I'd recommend using an input_select (a dropdown) with 3 modes and automations that respond to the new value each time it changes.
Having 3 'buttons' for it seems overcomplicated. If you want that because of the way it looks, I understand... if you just wanted it because you didn't know there were other options, consider the dropdown π
@waxen rune From that example, I'd guess you could go for a json template
what did you mean?
thanks @ivory delta I will give it a try
my sensor "sensor.vento_tosko" contain "10.4","km/h","EWE","17.5","Β°C","","","Italy"
I thought it looked like a json response, but it isn't. I think mono's way with index is the way to go.
when I arrange the value template with
value_template: "{{ states('sensor.vento_tosko') | string() | trim() | truncate(4,true,'') | float()/1.8 | round() }}"
How can i get the 4th value?
(instead of using TRUNCATE)
I'm bad with templates... but I'd guess something like this: {{ (states('sensor.vento_tosko') | string() | trim() | truncate(4,true,'') | float()/1.8 | round())[3] }}
Extra parentheses around the whole expression (because you're already returning a list/array), then pick an index from that list.
Someone else might suggest a more elegant way.
@waxen rune any more elegant way?
I think you could do something like this:
{% set foo = ["10.4","km/h","EWE","17.5","Β°C","","","Italy"] %}
{{ foo[0] }}
where foo[0] will give you the first value (10.4), foo[3] should give you the fourth
haven't really tried it, but I think it should work. gonna test in dev tools
That's what my suggestion does, bonehead π
No need to set it to a variable before doing the index. Just use the index.
sorry, didn't see your response
Intermediary variables are almost always a bad idea unless they're going to be used more than once.
i was tagged and responded..
ok i go to test the position of []
!
it was not an array but this '\n 0.0\r\n Km/h - SSW\r\n\n'
and i need to get the 0.0
{{your_thing.split()[0]}}
Hello. How can I make this template round to 2 decimals points? "{{ states('sensor.server_monthly_energy') | float + states('sensor.work_laptop_monitor_monthly_energy') | float }}"
preferable that its fixed at 2 decimals even if the last digit is a 0
preferable that its fixed at 2 decimals even if the last digit is a 0
@grim geyser Dont think thats possible. You have to use either of the one listed here https://www.home-assistant.io/docs/configuration/templating/#numeric-functions-and-filters
Oh ok thanks
I got another question.
Im trying to add 2 sensors but im getting a value way higher than it should be.
"{{ (states('sensor.server_monthly_energy') | float + states('sensor.work_laptop_monitor_monthly_energy') | float) | round(2) }}"
this is saying that 0.46 + 0.00 = 2.55
any idea why i have wrong? Tried changing parts but either it doesnt work or doesnt load
If you try {{ (states('sensor.server_monthly_energy')|int + states('sensor.work_laptop_monitor_monthly_energy')|int) | round(2) }} ?
nope. now gives me 2
I will keep trying it has work haha its simple math haha
im sure its something dumb im not seeing
Can you give the output of {{ (states('sensor.server_monthly_energy') }} and states('sensor.work_laptop_monitor_monthly_energy') ?
that fixed it. With what you said I realized that one of the sensors wasnt what I thought it was.
thanks
i knew it was something dumb. Sorry about that
Great it works! π
can i get some help moving the .png like this: https://ibb.co/CKjqRqd? Here is the template: https://pastebin.ubuntu.com/p/2GMTwQ2rsJ/
try position: absolute; in the image style attribute
you mean like this? <img width="200" height="200" src='/local/bilder/unifi/ap.png' style='position: absolute;' />
How should I write a template sensor that have state 0 for example if power consumption is under 3w on an entity and state 1 if its above 3w ?
{{ 0 if states('sensor.power_consumption') | float < 3 else 1 }}
oh, thanks.
I am trying to create a template message. Is it possible to filter entities somehow? I have 4 temp sensors, and want to include the entity name and lowest reading the last month, only if has been below 0 degrees....
Can someone let me know what I'm missing here? The goal is to create a binary_sensor that turns on when there is an event with a specific location (in this case 'Thuis'. It turns on, but stays on, causing it to not trigger again the next day.
- platform: template
sensors:
alisina_werk_thuis:
friendly_name: Alisina Werk Thuis
value_template: "{{ is_state_attr('calendar.werk', 'location', 'Thuis') }}"
Maybe I'm not using it correctlt or I'm missing something obvious.
@north acorn is the attribute always set to Thuis?
it needs to change from Thuis to something else in order for it to turn off
if that never happens, it will always be on and therefore never trigger again
@trail estuary yes that's possible
@mighty ledge hmm I see. Then I need to maybe create something that turns it off. Because it's a calendar event that is either on 'Thuis' or 'Kantoor'. But it can happen that it's 4 days in a row at 'Thuis'. I understand that the binary sensor does not update if the event is ended (since the event itself is not changed, but just stopped).
make a timed automation that checks the binary_sensor
if the binary sensor is on... trigger, otherwise don't
well the problem is that the binary sensor remains on
after the event is over
so it's on all the time
yeah, but if you do this at a set time every day....
maybe I'm making it more complicated than needed with a binary sensor template. I think it might be easier to use the calendar itself as an event trigger and then check the attribute state to call for action or not (I use Node-RED).
How do I force my template platform sensors and switches to refresh? I can't get HA to read updated sensor.yaml or switch.yaml files unless I select "reboot host system" from the supervisor tabs. None of the "YAML configuration reloading" option under the configuration tabs seem to do anything. I've check all the forums and google, but there seem to be lots of wishes and complaints but no answer....
I'll ask there, thanks @mighty ledge !
np
@robust saffron check your logs, are there errors?
the problem with most of those 'complaints' is that people don't check the logs for errors
they blindly assume the file is good
rule #1, if something isn't working, check the logs.
Do not rely on 'configuration check' either.
Thanks. Is that the Supervisor Log? I don't see any errors there.
No, the normal home assistant logs. Located in your config folder.
I believe they are in the UI under configuration -> logs
This is going to take a few minutes to load and scan as I have a known MQTT problem with an integrated device that creates an error message every minute π¦
you should look into learning how to suppress messages from the logs with logger
Yes. And I don't need so much debug info for stuff that is working either. OK nothing obvious there, but of course this is post a successful reboot. I'll sort out the log supression, excessive debug logging, then try to repeat my previous error, check the logs and come back here. Thanks.
I only have logs for critical issues
my logs are empty after days of running without restarts
If my repeated error message is 2020-11-05 13:17:21 ERROR (MainThread) [homeassistant.components.mqtt.climate] Could not parse temperature from Then I need to add homeassistant.components.mqtt.climate: fatal to my configuration looger: logs: and then reboot?
What's the full error message?
Also, what's your config for that integration?
Also, no need to reboot. You can use the service to set log levels: https://www.home-assistant.io/integrations/logger/#service-set_level
That is the ful error message. Nothing after "from". The error is arriving from an MQTT audo-discovered device which is actually an ESP286 talking to a Bosch central heating controller where I don't have a Room Temperature thermostat fitted. There is an Issue and a solution developing over here https://github.com/proddy/EMS-ESP/issues/582
@mighty ledge How would I approach that?
@trail estuary What templates have you tried so far?
@mighty ledge Sent you a DM
Please don't send unsolicited PMs. That comes across as rude and demanding of attention and tends to result in you getting blocked by the one you messaged
anyone know how to invert a binary sensor status? I've seen some forums about using a template but then it duplicates my sensor. I just want to modify the current binary sensor
wanting to invert a wyze contact sensor
thats definitely a job for a template, no other way I believe
@coarse tiger is there a way to use template but not duplicate the sensor?
how can I check if there's a value/string at blah[47].name i tried {% if blah[47].name is defined %}
not that I know of, the template gets it's reading from a entity and creates its own based on the template
@brisk temple is .name a attribute or the state?
and is there always an item at index 47
it's a json, so it would be attribute?
and no
that's my error, there's nothign there
UndefinedError: list object has no element 47
bla[47].name if (bla | count >= 46)
so you should check that it exists there before trying to access something below
{{ l[3] is defined }}```
-> False
the issue is i'm trying to loop through 2 arrays and the length is longer on one than the other
{% if blah[47] in blah %} fixed it
Hello. In a template can i round then keep adding more? for exampe. ((((1.7+1.2) round) + ((0.6+0.3) round))) round
because of percentages
money is only 2 decimals but percent can give you lots of decimals on each calculation when it needs to be roudned
eh, i think you're over thinking it
On paper I tried it with only 1 round at the end and it was off
It was only 3 cents but since Iβm building it for the first time I might as well get it exact. If I had to modify an existing template to correct it I would just leave it as is.
Rounding multiple times = bad
Thatβs how they do it on my bill
But itβs until mid next year
Because of the pandemic we are getting discounts on our electric bill. But not off the total, only certain parts
For example on the per kWh we are getting 22.86 percent off but just on that part
I still don't understand the need to round multiple times. But if it works for you...
Letβs see what happens. Iβm going to use the template builder
And try with various of my bills and see if it works out. Then change the variable for the sensors
Hi there!
Can anyone tell me how to passthrough secret into template?
For example, I have secret foo: 'bar' and I want to test if state of my sensor is equal foo. So I want something like:
{% set foo_var = !secret foo -%}
{{ is_state('sensor.foo_sensor', foo_var)}}
But that doesn't work obviously.
And I would prefer to escape creating input_text that contains secret like in this solution: https://community.home-assistant.io/t/how-to-use-secret-in-sensor-template/110510/4?u=hepoh
We discussed this topic here: #templates-archived message
in short, either you use an input_text, which you don't want, or you put the template in the secret file
I see, thank you!
Is this error because of the subtraction or because the templates dont result in real floats or whats the issue here?
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
for the template
{{ ((as_timestamp(states('sensor.one_a2003_next_alarm')) - as_timestamp(now())) /60) |round(1) }}
Try this part in developer-tools/template and make sure you actually have the right entity id as_timestamp(states('sensor.one_a2003_next_alarm')
thanks @charred dagger , thats what I always do and it works there. Still logs an error sometimes. Maybe the entity doesnt exist consistently? Idk... But what is the actual error message? I dont get what it actually complains about
It means as_timestamp(states('sensor.one_a2003_next_alarm') returns None but as_timestamp(now())) returns a number, and hass doesn't knowwhat none minus a number means.
I didn't read your entire message. Sorry.
{% set test = [1, 2, 3, 4, 5] %}
{% set n = 0 %}
{% for i in range (test | length) %}
{% if i + 1 <= test | length %}
{{ n }}
{% set n = n + 1 %}
{% endif %}
{% endfor %}
how come n = 0 in the for?
all 5 times
because logic
which i don't have
You need to use namespace if you want to do that https://jinja.palletsprojects.com/en/2.10.x/templates/#namespace
i'll check it out thx
@brisk temple what are you actually trying to do outsdie the test? There's very few cases where you need a for loop to count things
i have two rest sensors that are pulling json data, each of these have almost the same .name in it, but 1 is missing 3. I wanted to reference data from both of them so I was trying to increment n when the if the name isn't the list so it still pulled the correct information
@brisk temple can you just show the 2 objects? and point out the data?
of course, sec
Here's the data: https://pastebin.com/nC3Sdnep and https://pastebin.com/L6YuAB0S I'm trying to get participants[].name .fame and .repairPoints in the first and items[].donations in the second
there are 3 ppl in the second that aren't in the first, want to just ignore them
and they are in the same order? I doubt that
i put it in name order
{% set dd = state_attr('sensor.death_dealers_member_list', 'items') | sort(attribute='name') %}```
either way, just filter the second list to only contain the names of the first list
i have a filter for those names, but not sure how to take out the other data as well
{% set available = state_attr('sensor.riverrace', 'clan')['participants'] | map(attribute='name') | list %}
{% set dd = state_attr('sensor.death_dealers_member_list', 'items') | selectattr('name', 'in', available) | list %}
or you could just iterate through the list using available
{% for name in available %}
but even then, can you assure that the second list and first list agree on available names?
well, i think that first list will at some point have people who aren't on that second list
the API outputs all that have participated (first list) and resets on Monday morning
whether they have been kicked from second list or not
Ok, so do this
{% set participants = state_attr('sensor.riverrace', 'clan')['participants'] | map(attribute='name') | list %}
{% set items = state_attr('sensor.death_dealers_member_list', 'items') | map(attribute='name') | list %}
{% set available = participants | select('in', items) | list %}
{% set dd = state_attr('sensor.death_dealers_member_list', 'items') | selectattr('name', 'in', available) | sort(attribute='name') %}
{% set rr = state_attr('sensor.riverrace', 'clan')['participants'] | selectattr('name', 'in', available) | sort(attribute='name') %}
@mighty ledge 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
π
the available?
np
@old bough posted a code wall, it is moved here --> https://paste.ubuntu.com/p/SYF9NwNsjG/
why it doesn't work for me
when it is light on he perform the action and when it is off perform the action https://hastebin.com/widozeroki.yaml
Your automation doesn't have a trigger. Triggers are what cause actions to happen
service: automation.trigger
data:
entity_id: automation.svetla_podla_jasu
Then you're just manually triggering the automation which eliminates the point of an automation
trigger:
- platform: state
entity_id: light.obyvacka_svetlo
to: 'off'
yes I will run it manually I need to turn the light on and off with the same automation
Ah, you actually want a script then
this automation will turn on my light but he doesn't know how to turn it off
Yes, the syntax is wrong for that. You'll want to use choose: (and you really want to make this into a script since an automation without a trigger is pointless)
I start automation with this on_multi_click:
`- timing:
- ON for at most 1s
- OFF for at least 0.2s
then:
- homeassistant.service:
service: automation.trigger
data:
entity_id: automation.svetla_podla_jasu `
Yes, what I'm saying is what you really have here is a script. You can turn what you have into a script and call the script instead in that code
What you have works (once the syntax is fixed), but it's better suited for a script
Oh and this is #automations-archived discussion
I'm trying to get the time when a binary_sensor was 'on' the last time.
Using states.---.last_changed includes the state being unavailable which I don't want. Whats the cleanest way to do this? π
Make an automation that records the current time to an input_datetime when the binary sensor goes to on
I need a condition
when turned off, perform the action
when turned on, perform the action
in one automation
Make an automation that records the current time to an input_datetime when the binary sensor goes to on
Oh, that makes sense. Is there no default state object for this? I don't want to have too many automations
No such thing as too many automations π
hahaha
There's nothing specific like that for the last time it was in a certain state, no
oh, okay. Thank you very much!
Uhh, I want use that time to have an automation condition like only trigger when sensor was 'on' in the last 3 minutes.
I'm writing an automation atm but I'm wondering whether putting the time into a input.datetime is the best idea here. Isn't a UNIX Timestamp (that is seconds since 1970 right?) better suited for this?
coz I could simply subtract the seconds? or am I overseeing something?
https://hastebin.com/cobokesuju.less thank you it works i'm happy
again, you can just use a script for this (see what i provided in #automations-archived)
@buoyant pine I'm gonna tag you really cheekily, sorry in advance. π¬ What do you think about my idea?
You can convert it to a timestamp and find the difference in seconds, yes
ahhhh π€¦ββοΈ thank you
It's me again!
I'm stuck! I want a template to check whether it is currently between input_datetime.bedtime and input_datetime.wakeup .
Google and the forums didnt help, because both input_datetime entities are obviously time-only, no date!
@teal cove does it need to be a template? what is the ultimate goal?
if you want to use it in an automation condition, you can just use them in a time condition: https://www.home-assistant.io/docs/scripts/conditions/#time-condition
Yes, I want a template but its hard to explain haha. Yes, conditions are easy (as I found out today)
But I think this template would be WAY too complex, as it would need to get either yesterdays bedtime and todays waketime or todays bedtime and yesterdays waketime depending on whether it is currently before/after midnight.... π³ π₯΄ way to complicated
why does it need to be a template?
Simply put, because I want a template sensor to carry a different number, depending on time of the day ^^
for what purpose? i'm trying to see if there's another solution here
and making sure this isn't an example of the XY problem...
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.
Yes, I see what youre asking :D lemme explain
To be exact, I want the sensor to be 'input_number.volume_nighttime' at night (duh) and 'input_number.volume_daytime' at day.
Then I want to use that volume in an automation: media_player.set_volume to the volume saved in the sensor
But I think I'm on to something here π I got a clue
You may be trying to put automation logic into a template
yuh π¬ π¬ π¬
yeah, just use templating to determine which input_number value to use
why would you need to put a template in a template?
well idk
yeah, just use templating to determine which input_number value to use
@buoyant pine what would that look like?
schematically
- service: media_player.set_volume
entity_id: media_player.whatever
data:
volume_level: "{{ states('input_number.daytime') | float / 100 if YOUR TEST FOR DAYTIME HERE else states('input_number.nighttime') | float / 100 }}"
is_state('sun.sun', 'above_horizon')
```?
thank you for putting this much effort into my stuff :D
ugh no it's not really "day"time but rather the timespan between my bedtime input_datetime and my wakeup input_datetime
how much precision do you need there? you could check if now().hour is between the hours in those input_datetimes
that is TOTALLY fine
i mean, half hours would be cool but thats really it
/not neccessary
so, make a test that converts the input_datetimes to just the hour and compare that to now().hour
but I'm afraid that the problem is gonna be that bedtime is on e.g. May 4 but wakeuptime is on May 5, you know?
ah yeah, that is a bit tricky
how much variation is there, and how important is it that it's close to that?
I dont understand
i'd almost say just make a time of day sensor (which has a fixed start/end time) and be done with it lol
or if you really want to, make an automation that turns a boolean on/off based on the input_datetimes
and use the boolean in the automation
if I could set the TOD starts/ends with an input number, nice, but thats not happening I guess :D
Good Idea!
I'll first try to have two input_datetimes with date+time and have an automation set the date every day. (time staying the same)
Then convert the two input_datetimes to unix timestamps and check if timestamp.now is in between
Man, PITA and I ain't talking about bread
actually yeah, you can just compare raw timestamps. not sure why i said to compare hours only
that'd do it
as_timestamp(states('input_datetime.bedtime')) < as_timestamp(now()) < as_timestamp(states('input_datetime.wakeup'))
yeah that was my Idea in the first place BUT
if you have an input_datetime with only the time specified, the associated timestamp is not from 1970 but from today....
true
then I tried adding the timestamp from today(midnight)
then I realised that that is dumb, because if it is after midnight, I need to add the timestamp of yesterday
tbh i'd say just use the automation idea with flipping a bool
haha
then it doesn't matter that it only has a time
I'll try my version with input_datetimes with both date+time specified
automation + bool == profit
and if it doesnt work out, I'll do bools :D
got it
{{ (state_attr('input_datetime.nighttime_start', 'timestamp')) < as_timestamp(now()) < (state_attr('input_datetime.nighttime_end', 'timestamp')) }}
evaluates True if its nighttime
hence
{% if (state_attr('input_datetime.nighttime_start', 'timestamp')) < as_timestamp(now()) < (state_attr('input_datetime.nighttime_end', 'timestamp')) -%}
Night vol: {{ states('input_number.volume_nighttime') }}
{%- else -%}
Day vol: {{ states('input_number.volume_daytime') }}
{%- endif %}
hello, why this is not working
entity_id: media_player.livingroom_tv
data:
source: "{{ input_select.livingroom_tv_source }}"```
I have a valid input_select values
but it wont change on my TV source
does it work if you replace the template with a static value? just to rule out other errors
I have another question
is there a way to declare variable in the script itself?
what Im trying to accomplish: if "{{ states('input_select.livingroom_tv_source') == "SBB BOX" }}" => then set source SBB BOX
else set source for TV Audio
You want to detect changes in the input_select and change something else based on the result?
please view my updated pseudo code
yes, basically if one option selected (SBB BOX)
So... a script? That's also #automations-archived territory.
then set SBB BOX for the source
everything else is set in input_select, set TV AUDIO
well, actually I wanted to do that like template
I think I just need an if statement?
but Im not sure if I can put template into variables: section
as input param to another script?
Hi guys!
I'm using this template is_state_attr("media_player.chromecast", "app_name", "Netflix") as a condition and it's working. But this one is_state_attr("trigger.from_state.state", "app_name", "Netflix") doesn't work (with state-change of media_player.chromecast as trigger), even when configuration says it's ok. Is it just buggy or isn't this working in general as a condition?
trigger is a variable, not a string. Try is_state_attr(trigger.from_state.state, "app_name", "Netflix")
Thinking about it... you probably don't want the .state either, since that represents the state value, not the state object.
ah ok, makes sense. But media_player.chromecast is a string? Ok.
Just tried both versions, without quotation marks and without .state, neither of them worked...hmm.
When you know the name of the thing, you give it as a string.
If you don't know the name and you're using a reference to a variable, there are no quotes.
true, thats a general principle. but as media_player.chromecast has also attributes my IT-mind would assume, that it is also some kind of variable π but I think I understand as what it serves in this context.
so it seems like I can't archieve what I want. probably I but the app_name into an input_text-helper or something like that...
Where are you testing this?
in an automation directly, as the trigger.from_state-stuff doesn't work in the template-tester-devTool. Or what do you mean?
currently looking like this: https://hastebin.com/ufeteriqow.yaml
(the elevation-condition is currently given ;))
I also just made attempt3 like you may see: without .state but with quotation marks
The quotes will not work.
So something else is wrong. Stop adding quotes.
This is an example from one of my automations:
action:
service: "homeassistant.turn_{{ trigger.to_state.state }}"
data:
entity_id: group.landing_switches```
Actually, a better one that uses the helper functions:
- wait_template: "{{ is_state(trigger.to_state.entity_id, 'home') }}"```
Use that... trigger.from_state.entity_id instead of a specific name with quotes.
ok, is think i understand what you mean. Then I I'll try that now: is_state_attr(trigger.from_state.media_player.wohnzimmer, "app_name", "Netflix")
Yup, "no" π Error during template condition: UndefinedError: 'homeassistant.core.State object' has no attribute 'media_player'
ahhh click-noise
When you use a trigger, both the to_state and from_state are an instance of a state object: https://www.home-assistant.io/docs/configuration/state_object/
that's it π₯°! Thanks a lot. And learned again something...great.
Need some help: I'm running a templated switch that is controlling a garage door relay. I've got all the logic right, but when I call for "switch.turn_off" on the template, it runs the turn_off function regardless of whether or not the switch is already off. I need it to run only when the switch is truly on, because if I hit the turn_off service, it triggers the relay to fire and will open it.
@lofty orchid posted a code wall, it is moved here --> https://paste.ubuntu.com/p/SmgtbKtVYR/
Figured it out, code is in the paste. If someone would look it over, I'd appreciate it. I know lots changes over time.
can I list who are currently in a zone with a template?
Hi all - on reflection, I think this is a template question - hopefully just a quick steer needed to the right template, card etc.. I've got Hue lights in every room and I've got a tab in Home Assistant for each room in the house. I have made picture buttons for quickly setting the scenes in each room which works great, however given the scenes are standard across the whole house, is there a way to have a single place for these template elements and then just load them into entity cards dynamically
How could I change this command to show Power on Years instead of hours? (Hours / 24 / 365 = Years)
for drive in $(ls -la /dev | grep -Ev 'sda|sd[a-z][0-9]' | grep sd[a-z] | awk '{print $10}'); do hours=$(smartctl --all /dev/${drive} | grep Power_On_Hours | awk '{print $10}'); echo "Power on Hours for ${drive}: ${hours}"; echo ''; done
Ehlo, I guess I found a bug in the template engine. I got the following template:
{{ (('group.climate_ripoux' | expand | sum(attribute='attributes.current_temperature')) / ('group.climate_ripoux' | expand | length)) | round(precision=1) }}
It works inside the template tester in the UI but not in a template sensor. I got the error:
invalid template (TemplateAssertionError: no filter named 'expand') for dictionary value @ data['sensors']['ripoux_avg_target_temperature']['value_template']
Should I open an issue in Github ?
Hi All, I'm quite new in HassIO and trying to automate my heaters. They are using a pilot wire, I want to manage 4 states (so I need two relays). I so declared several switch (from raspi gpio port) 2 per heater. Then I created one input_select per heater with 4 states (comfort, eco, antifreeze and off), I created then 4 automations per heater (one per state) with two actions on each (two service: switch.turn_[on|off]. I've got 5 heater in my house; so this method implies to generate 5x4=20 automation for now, just to switch states; on top of that I want to have an "away" mode to set all heater to unfreeze; then I want to change heater on some different triggers : time of the day, day of the week, if I am consuming too much electricity at a specific moment (eg deactivate one of two heater when using my oven and baking tray at the same time etc)
I have the feeling that template could help me to minimize automations to create in my context and simplify my configuration. Can I create a "super automation" for each heater/input_select that depending on the "to" value could set the relays (switch) like this :
- Comfort = switch 1 off; switch 2 off
- Eco = switch 1 on; switch 2 off
- Antifreeze = switch 1 off; switch 2 on
- Off = switch 1 off; switch 2 off
Make a climate for each switch and use an automation to switch to heat mode for the eco and antifreeze mode maybe ?
For reference I opened an issue in Github for my question https://github.com/home-assistant/core/issues/42966
@thorny snow Look up Schedy
@lusty forge and @ivory delta thx a lot, I'll have a look closer on the doc for these topic !
@thorny snow You're welcome ! I read a bit closer on your ask and I think you should use a generic thermostat with a script with parameters. That would make one script and make the rest very simple.
@lusty forge got it, will test.
Even with a generic thermostat, automating anything beyond a very simple 'on/off mode' is going to be complex. Schedy takes care of all the stuff you'd have to consider in automations (missed triggers, presence detection, seasonal modes, etc).
@ivory delta; I do not think wanted to managed individually all my heaters using a pilot wire is something unusual. I mean I should not be the only one wanted to schedule this kind of stuff (except maybe regarding the total house consumption). My feeling, is that HA is really wonderfull tool and full of capabilities, I am maybe not taking the problem in the right way... If my request feel strange, please let me know, I am not yet good engouht in HA to be sure thinking my need in the right way.
@thorny snow No, your issue is super normal and quite frankly HA should be able to handle that. Having only two switch per thermostat is normal and if HA can't handle it I would personally prefer to suggest an improvement in the core or in a custom component to handle that.
I was in the middle of handling two installation on a piped circuitry with one burner and 7 radio thermostat with lag and Schedy looked cool but overkill even in my case
HA handles most of your situation. It allows you to integrate devices and control them in one place (instead of loads of different apps). I'm just suggesting that there are better tools for climate schedules than HA automations.
HA automations are trigger-based. Schedules aren't.
But it's your choice... build it with HA automations if you want, just don't be surprised when it's not reliable.
@lusty forge ok, sure, I am totally sure that HA can do it, and if not, I will directly raise an issue and wok on a patch ^^
My reflexion was more about my way of think with homeassistant. I think since there is 2 relays, I need to declare two switch (no other way), then to have a selector between 4 choices, I only see inpu_select; then everything is working for me now, but with a huge amount of automation on-top, my question right now was is there a way to generate some "generic" automation based on templates to avoid having too much automations declared in conf
In my need, I do not need some temperature sensor to act as a thermostat. I "just" to play with my heater modes and change them with one button, of automate some basic schedule on it.
I do not really understand well how template is working... IIUC I cannot generate some automation in jinja, but need to create an automation for an heater then I would like to have some "if" to take differents actions regarding which "to" value has been set in the input_select.
I'd like to change two inputs regarding the "to" value of one input_select
Oh I understand now ! Just a simple operation. Use the new switch-case thing they added recently. That can be easy
ok, ^^ thx will have a look on that now
@lusty forge Yep, thx a lot this fit exactly my need for now !!! I should have more RTFM ! sry @ivory delta I will continue to check Schedy; I have a feeling that you are too far ahead of my need for me to understand now ^^
Quick question - is there a way to create a dynamic variable in templates? I'm creating some that are getting pretty long and reference an element multiple times, so I'm conscious it'll be a pain to manually update if these change, eg the lounge_pair name here: https://paste.ubuntu.com/p/cn46CCVZpg/
Ideally I'd just add a reference at the top of the template and then use this throughout - this'd mean I could just update in one place in future?
Then those docs are valid. Patch versions usually don't change functionality.
i see my problem, I was trying to use an ansible function
I have an entity attribute which gives out its information as a list like this
[{'direction': 'Stuttgart', 'departure_time': datetime.datetime(2020, 11, 8, 21, 29), 'product': 'S', 'minutes': 28, 'line': 'U1'},
{'direction': 'Stuttgart', 'departure_time': datetime.datetime(2020, 11, 8, 21, 44), 'product': 'S', 'minutes': 43, 'line': 'U1'}]
How Do I convert this so that I can use these values as usual? Actually, I only need the time (21:29 and 21:44) and/or the 'minutes' value (28,43)
Glad for any help! π
try state_attr('sensor.sensorname', 'minutes')[0]
no no, the thing itself is an attribute.
I get this list when I do {{ state_attr("sensor.departures", "next_departures") }} ...
{{ state_attr("sensor.departures", "next_departures")['minutes'][0] }}
ohh that breaks it down to one list
[1] for the second line
yes of course :D
but that still gives me one line of list, which I dont know how to handle
{'direction': 'Stuttgart', 'departure_time': datetime.datetime(2020, 11, 8, 21, 29), 'product': 'S', 'minutes': 28, 'line': 'U1'}
what are you looking to do? i thought you wanted the minutes
oh wait I didnt read properly
If I do what you said it says UndefinedError: 'list object' has no attribute 'minutes'
something like this:
{% set ns = namespace(minutes=[]) %}
{% for element in data %}
{% set ns.minutes = ns.minutes + [element["minutes"]] %}
{% endfor %}
{{ ns.minutes }}
[28, 43]
what were you looking for?
youre on the right track, I just dont know how :D
you asked for a template that returned that π
do I copy paste that below this
{{ state_attr("sensor.departures_to_marienplatz", "next_departures") }}
?
replace data in the second line with state_attr("sensor.departures_to_marienplatz", "next_departures")
Thats IT
TemplateSyntaxError: expected token ':', got '}'
wait
maybe add [0]
nah, that didnt do anything
I don't know what to do with datetime.datetime in there, so I just removed them. I don't know if that would be a problem outside of the template editor
paste this into
-> Templates:
{% set data = [{'direction': 'Stuttgart', 'departure_time': (2020, 11, 8, 21, 29), 'product': 'S', 'minutes': 28, 'line': 'U1'},
{'direction': 'Stuttgart', 'departure_time': (2020, 11, 8, 21, 44), 'product': 'S', 'minutes': 43, 'line': 'U1'}] %}
{% set ns = namespace(minutes=[]) %}
{% for element in data %}
{% set ns.minutes = ns.minutes + [element["minutes"]] %}
{% endfor %}
{{ ns.minutes }}
SORRY
IM so stupid xd
1 sec
AHH its working
Thank you so much guys @inner mesa @brisk temple !
If I want the actual departure time, is it easier to add the 'minutes' to the current time? or am I better of using 'departure_time' some how (I don't know how)
I always wondered how to extract numbers out of a string properly...
To address the XY problem:
Ultimately I want a sensor carrying the information:
sensor.blabla state 21:29 attributes:
time_1: 21:30
minutes_1: 6
line_1: U1
time_2: 21:45
minutes_2: 21
line_1: U2
etc
yeah, was about to ask what you were planning to do with it
π¬ populate a card with it
there's undoubtedly a better way, but:
{% set data = [{'direction': 'Stuttgart', 'departure_time': 'datetime.datetime(2020, 11, 8, 21, 29)', 'product': 'S', 'minutes': 28, 'line': 'U1'},
{'direction': 'Stuttgart', 'departure_time': 'datetime.datetime(2020, 11, 8, 21, 44)', 'product': 'S', 'minutes': 43, 'line': 'U1'}] %}
{% set ns = namespace(minutes=[]) %}
{% for element in data %}
{% set time = element["departure_time"].split(',') %}
{% set hour = time[3].strip() %}
{% set min = time[4].strip().strip(')') %}
{% set ns.minutes = ns.minutes + [hour + ':' + min ] %}
{% endfor %}
{{ ns.minutes }}
['21:29', '21:44']
I'm really just hacking around in the template tool and googling, BTW
I'm trying to understand the magic you put in there, gimme a sec
thank you so much
okay I think I understand
if there was a way to turn that datetime.datetime(xxx) into an actual datetime object, this would be much easier
yes, but If you dont know a way, I sure dont
but yours looks quite clean
okay If I put this into a template sensor, for each attribute I paste the whole thing but in the last line I do {{ ns.minutes [0/1/2/3...] }} right?
for the state?
for the attributes. I can template attributes I think
yes, but you can also use native data types in attributes. So you should be able to just set the attribute to the output of that
googling that
the docs only say that this integration is available from the UI now :D
yes
I'm just giving that as an esamle
example
point is, you can have a list in an attribute
but I dont want it as a list, I want it as "clean" states
I think you'll have to play around with it
Okay, will do! Thank you!
One more thing tho: If I do
{% set data = state_attr("sensor.departures_to_marienplatz", "next_departures") %} instead of the text like you did, it says UndefinedError: 'datetime.datetime object' has no attribute 'split'
same thing if I just replace data with the state_attr
if you want them as separate attributes, then yes, just create additional attributes with different indicies
@inner mesa posted a code wall, it is moved here --> https://paste.ubuntu.com/p/cJTq8Sd5PH/
Thank you so much again! Just the one thing with replacing data ... π¬
it looks like it is interpreting datetime.datetime(xx) as an object
where are you testing that?
thats what I thought
I'm just gonna try it for real, maybe its a template tester bug π€·ββοΈ
but is {% set data = state_attr("sensor.departures_to_marienplatz", "next_departures") %} the correct syntax?
I'm really just Googling at this point. If you have access to a real datetime object, then you can call things like .hour .minute, etc.
I'm just gonna try it for real, maybe its a template tester bug π€·ββοΈ
nope, test_attribute: null
but its not a real datetime obj but just a string?
not based on the error you provided
or are you saying I should test .hour etc?
this is becoming much harder for me to guess at what's happening on your system
yeah
see the docs above
π
will do
Thank you so much tho, can I 'buy you a coffee' for your help? It would have taken me days and hours to get this far alone....
nope, happy to help. but I just can't easily reproduce your system and I'm spending more time trying to do that than actually solving the problem at this point
hahaha
I imagine
It doesnt eat ``` {% set ns = namespace(minutes=[]) %}
{% for element in state_attr("sensor.departures_to_marienplatz", "next_departures") %}
{% set time = element["departure_time"].hour %}
{% endfor %}
{{ ns.minutes }}````
my guess is that if you're getting that error, then rather than treating the datetime object as a string, you should treat it as a datetime object
at some point, I would just write a python script for it
I can barely handle yaml and magic is not my type of soup
should element["departure_time"].hour work? or am i off the tracks
that's what I would have tried
wait it does something, If I'm not stupid
{% set ns = namespace(minutes=[]) %}
{% for element in state_attr("sensor.departures_to_marienplatz", "next_departures") %}
{% set time = element["departure_time"].minute %}
{% endfor %}
{{ time }}
prints 7
(I had {{ ns.minutes }} before π€¦ββοΈ)
I dont get it at ALL haha
ok
if that works, it's a much better solution than trying to dissect the string
yes!
ty
now the adding of hour and min doesnt wanna work
{% set ns = namespace(minutes=[]) %}
{% for element in state_attr("sensor.departures_to_marienplatz", "next_departures") %}
{% set hour = element["departure_time"].hour %}
{% set min = element["departure_time"].minute %}
{% set ns.minutes = ns.minutes + [hour + ':' + min ] %}
{% endfor %}
{{ ns.minutes }}
"doesn't wanna work" is too vague
then fix that π
Youre teaching me, I like that
hour|string + ':' + minute|string
almost what I thought of :D
or do that in the initial assignment
you can add a format to fix 23:7, but I'd have to look it up
doesnt say anything on the blogpost
but honestly, I'll take anything that works at this point π
did that, tahnks!
something like: {% set min = "%02d" % element["departure_time"].minute %}
nevermind lol
then it's already a string
no no it was working, I thought the 07 value went to 10
and I couldnt see if it worked
but the 07 is still there, I'm just blind
thanks!
I'm soo close to getting it
thank you Rob, youre the man!
One thing on https://www.home-assistant.io/docs/configuration/templating/ is missing I think, datetime object to datetime object with different format
or does one just stitch them together e.g. with .hour + .minute
there's an entire section on formatting time: https://www.home-assistant.io/docs/configuration/templating/#time
yes, thats what I'm looking at
but
there is datetime to UNIX and the other way around
but datetime to datetime is missing, or isnt it?
basically 2020-11-08 23:07:00 to 23:07
this is probably the closest: timestamp_custom(format_string, local_time=True)
you just need to turn it into a timestamp (as_timestamp())
ah, to timestamp and then back again
strftime() can do what you want, but I don't think we have that
yes, i think so. whats the syntax on that?
but like I said, I don't think we have that
ok
when using local_time=True it says TypeError: timestamp_custom() got an unexpected keyword argument 'local_time'
even though thats exactly what the docs say
it seems like local time is the default anyway tho
I am trying to make a template for calculating how long my burner is running for between three different floors. I have the math formula but haven't been able to implement it as a template with the actual entities. Is there like a tutorial on how to do this. I was trying with float options but I keep getting errors while trying to build the full template
What I need is a xzKa/(a+b+c)* where almost all variable will be entities in HA
@fast mason I would suggest something like this. If you make sure that all your values evaluate in Dev Tools, it should be rather straight forward doing the math.
value_template: >-
{% set t1 = (states('sensor.burner1') | float ) %}
{% set t2 = (states('sensor.burner2') | float ) %}
{% set t3 = (states('sensor.burner3') | float ) %}
# And then the actual math, not your case below
{{ ((t2-t1)/(t3-t1) * 100) | round(2) }}
Wow that is so much more elegant than what I've been trying to write
states('input_number.hourly_burner_consumption') | float *
states('sensor.burner_hours') | float *
states('sensor.ground_floor_hours') | float) /
(states('sensor.ground_floor_hours') | float +
states('sensor.first_floor_hours') | float +
states('sensor.second_floor_hours') | float))}}
round() didn't seem to round anything. I had 10+ decimals. But this thing in the beginning seems to work instead
I'll try converting what I have to the way your example is. It's a lot easier to read π
hello guys. i have a led light connected via my esp32/gpio. i am using homeassistant automation to increase/decrease its brightness throughout the day. i am trying to figure out a way to read off current brightness of my led and use in a template sensor such that i can then maybe graph that value in lovelace or do other functions with it. as far as the template help page on homeassistant website, it is very well documented and self explinatory but i myself am falling short of being able to implement using the exmaple for my specific scenario. Any help would be apprecaited.
Unfortunately not sure about that. Although I am interested to see how you increase/decrease it the brightness throughout the day
I only have a very simple thing to turn on the lights if brightness goes bellow a set value
you can use automation and use the device brightness on property. let me post an example.
but i think i should send you a pm instead because this room is for template convo
so here is what i have guys but i am unable to see the brightness value:
- platform: template
sensors:
blue_brightness_value:
friendly_name: "Blue Brightness Value"
unit_of_measurement: '%'
value_template: "{{ state_attr('light.blue_spectrum_brightness', 'brightness_pct') }}"
Anyone can give me hints on what am i doing wrong.
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.
oh ok but how is it possible to set a value for brightness_pct in automations etc.
is there another way to grab this value. like on_update or something and then pass on to a tempalte sensor.
You can just convert the brightness attribute to percent by dividing it by 2.55
Or just use brightness in the service call
What are you ultimately trying to do here though?
bascially my lights are connected pwm via my esp32. i am using automation to set brightness values through the day. i want to be able to read those same brightness values such that i can use them to graph in lovelace
sorry didnt see your messges above. changing it to brightness as attribute works. thank you for the hint
much appreciated.
Hi iΒ΄m trying to use the mobile app as an input for an alarm clock that turns on the light iΒ΄m currently stuck on the comparism of the values
How do i convert from Mon Nov 09 20:00:00 GMT+01:00 2020 to xxxx-xx-xx xx:x
so i can compare it to the date_time ?
how are you getting the value?
best method would be to convert both of them to python datetime objects and compare that way
whats the best way to not show decimal values for value_template: i tried 'round' attribute but that does not work.
my config does not pass when used.
~share your code
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
here is my code for template sensor https://paste.ubuntu.com/p/RrM3MRxmyk/
there's no such thing as round: xx, which is why it was failing config check
making stuff up π
value_template: "{{ (state_attr('light.blue_spectrum_brightness', 'brightness') / 2.55)|round }}"
gotcha. thank you
First time using templates, so apologise in advance for whatever stupid simple wrong thing I have messed up here. I'm trying to use the London Air documentation and am following their guidance on setting up sensor data
Broken code there
Supposedly there's issues with multiple lines π©
No issue with multiple lines. Your issue is that you need to mix quotes.
'{{state_attr('sensor.havering', 'data')[0].pollutants[0].summary}}' is bad. The second apostrophe closes the first, leaving the rest a steaming pile of gibberish.
"{{state_attr('sensor.havering', 'data')[0].pollutants[0].summary}}" is good, the closing speech marks are right at the end, and apostrophes in the middle don't matter.
That makes loads of sense
Also, it doesn't matter which way round you do it. '{{state_attr("sensor.havering", "data")[0].pollutants[0].summary}}' is equally valid.
what would be the code for converting that Tempate String <template TemplateState(<state sensor.jkm_lx2_nachster_wecker=2020-11-10T19:00:00.000Z; Local Time=Tue Nov 10 20:00:00 GMT+01:00 2020, Package=Unknown, Time in Milliseconds=160503.... currently iΒ΄m getting 1970-01-01 , 00:01:00 but i need 2020-11-10, 19:00 iΒ΄m using {{ (states.sensor.jkm_lx2_nachster_wecker | int | timestamp_custom("%Y-%m-%d , %M:%H:%S")) }} Where is my Mistake ?
states('sensor.jkm_lx2_nachster_wecker')
Or states.sensor.jkm_lx2_nachster_wecker.state but what I put is recommended
Or
states.sensor.jkm_lx2_nachster_wecker.statebut what I put is recommended
@buoyant pine Better but still not perfect result is 2020-11-10T19:00:00.000Z need ist to be like : 2020-11-10 19:00:00
might need a strptime -> strftime sequence
@prime sphinx there is a good example in dev tools demo template:
{{ as_timestamp(strptime(state_attr("sun.sun", "next_rising"), "")) | timestamp_local }}
or another variant:
{{ state_attr("script.store_startup_time", "last_triggered").strftime("%Y-%m-%d %H:%M:%S")}}
https://strftime.org/ is a good place if you need other combinations.
{{strptime(states('sensor.jkm_lx2_nachster_wecker'),"%d/%m/%Y")| timestamp_local }} has the same reesult 2020-11-10T19:00:00.000Z
with the {{ state_attr("script.store_startup_time", "last_triggered").strftime("%Y-%m-%d %H:%M:%S")}} iΒ΄m not getting any further looking on it all day without revelation...
@prime sphinx ok, can we try a few things?
@waxen rune shure iΒ΄m happy to get help
{{ as_timestamp(strptime(states("sensor.jkm_lx2_nachster_wecker"), "")) | timestamp_local }}
if you test that in dev tools > template
that hit the nail right on the head...
everything's fine?
2020-11-10 21:00:00 yep perfect now i can work on the rest thank you so much π
Im curious
what is timestamp value
I mean like
- platform: template
value_template: >
{{ now().timestamp() - as_timestamp(states.binary_sensor.motion_sensor_frontdoor.last_changed) < 45 }}```
I noticed while I was testing this template in templates tab that it doesnt represents seconds?
I need just to grab "timeframe" when sensor is triggered next 15 seconds
I put 45 just for testing purposes
It's epoch time
The number of milliseconds since the start of the year 1970. It's how computers track time.
If you're comparing two timestamps, you need to multiple your seconds by 1000.
{{ now().timestamp() * 1000 - as_timestamp(states.binary_sensor.motion_sensor_frontdoor.last_changed) * 1000 < 15 }}
like this?
oh yes
lol π
and famous problem for unix machines and dates for 2032
or 2034. year π
I forgot
Signed integers. D'oh.
And of course there's one for that too
There's an xkcd for everything
Your first one only really works for American English speakers though π
Real English speakers don't pronounce 'epoch' like 'epic' π
You mean ee-pic?
Good day all. So I am in the template browser trying to formulate a calculation and it is almost working as expected. {{((states.sensor.us_coronavirus_deaths.state | int) / (states.input_number.us_pop.state | int)) | float }} <<< that works but it is giving me the output of 0.0007219727272727273 and I would like it to be a percentage value with maybe 5 decimal places Any tips for this?
reading the jinja2 page and the templates page and something is eluding me I am sure
| round(5)
Hi im running homeassistant supervised on ubuntu and trying to fire a shell script on another machine. but get this error: 2020-11-10 15:15:46 ERROR (SyncWorker_0) [homeassistant.components.command_line] Command failed: ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.57 /home/pi/scripts/get_kitchen_fan_light.sh
this is my yamL: - platform: command_line
name: kitchen_fan
command: "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.57 /home/pi/scripts/get_kitchen_fan_light.sh"
and from the terminal that works:
system@hass-dev:/usr/share/hassio/homeassistant$ ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /usr/share/hassio/homeassistant/.ssh/id_rsa pi@192.168.1.57 /home/pi/scripts/get_kitchen_fan_light.sh
Warning: Permanently added '192.168.1.57' (ECDSA) to the list of known hosts.
0
IIRC there's problems with ssh commands since hass runs as root within its container...
I'm not sure. I solved it at some point by building my own container that runs as a user... but that's not really an option in supervised installs, I believe.
I just thought maybe knowing more about a potential cause of the problem could help in finding a solution.
works fine for me in supervised
- platform: command_line
name: HostTemperature_Rpi4
command: ssh -o ConnectTimeout=20 -i /config/ssh/id_rsa -o StrictHostKeyChecking=no pi@ip "/bin/cat /sys/class/thermal/thermal_zone0/temp"
unit_of_measurement: "ΒΊC"
value_template: '{{ value | multiply(0.001) }}'
scan_interval: 600```
hm looks like my config