#templates-archived
1 messages · Page 6 of 1
Hi Guys.
i want to make a automation that will make some kind off value template
in that i need to work with with the now time.
i used cod but no sucess
{% set start_time = (state_attr('input_datetime.followers_start_time', 'timestamp')|int ) %}
{% set now_time = (state_attr('sensor.time', 'timestamp') |int ) %}
{% set runned_time = (now_time - start_time) %}
{{ runned_time | timestamp_custom('%H:%M') }}
can someone help me??
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
Please format your code as code
You can perform the tests in #botspam
here is my example
action:
- service: input_datetime.set_datetime
entity_id: input_datetime.followers_runned_time_since_start
data_template:
time: >
{% set start_time = (state_attr('input_datetime.followers_start_time', 'timestamp') | int ) %}
{% set now_time = (state_attr('sensor.time', 'timestamp') | int ) %}
{% set runned_time = (now_time - start_time) %}
{{ runned_time | timestamp_custom('%H:%M') }}
This should do the trick
{{ (now() - states('input_datetime.followers_start_time') | as_datetime | as_local).time() }}
Corrected above
i will try
i looked over the derivative sensor i may try that also. I noticed my 10 minutes ago sensor is not showing but my 24 hour ago sensor is working. i am not sure what is different i need to dig a little deeper.
- name: Rain 10 Minutes Ago
unit_of_measurement: in
value_template: "{{ value | float }}"
group_function: first
measurement: '"autogen"."in"'
field: '"value"'
where: 'time > now() - 10m AND "entity_id"=''atlas_rain'''
- name: Rain 24 Hours Ago
unit_of_measurement: in
value_template: "{{ value | float }}"
group_function: first
measurement: '"autogen"."in"'
field: '"value"'
where: 'time > now() - 24h AND "entity_id"=''atlas_rain'''
No sorry, I'm obviously a bit tired
Got that error
AttributeError: 'NoneType' object has no attribute 'tzinfo'
{{ (now() | as_timestamp - state_attr('input_datetime.dishwasher_program', 'timestamp')) | timestamp_custom('%H:%M') }}
Replace it with your input_datetime
Many thanks
that work
Quick then 😉
action:
- service: input_datetime.set_datetime
entity_id: input_date.followers_position_requested
data_template:
numeric: >
{% set time_now = (state_attr('input_datetime.followers_runned_time_since_start', 'timestamp') | int ) %}
{% set time_move = (state_attr('input_datetime.followers_movements_time', 'timestamp') | int ) %}
{% set step_pos = (time_now / time_move) %}
{{ step_pos }}
i Want that division of the times give-me a numeric value
is taht wiat the correct?
is that way correct?
data_template has been depreciated for over two years, you can just use data:
And numeric is not valid for an input datetime
Also number is not valid, should you not use an input_number here
An input datetime expects a date, a time, or both
maybe i dont tell you right what i want
i have two input_datetime that i want divide to get a numeric value
You're just not following the docs for that service call
There's no 'numeric' or 'number' in there as a parameter
service: input_number.set_number
entity_id: input_number.followers_position_requested
data:
number: >
{% set time_now = (state_attr('input_datetime.followers_runned_time_since_start', 'timestamp') | int ) %}
{% set time_move = (state_attr('input_datetime.followers_movements_time', 'timestamp') | int )%}
{% set step_pos = (time_now / time_move) %}
{{ step_pos }}
what you think?
I think you are now not following the docs for an inout_number
You are making things up
i don't understand...
Look at the docs and see if set_number is a thing, you’ll find that it isn’t and you’re making up what you think is correct
@stone bane posted a code wall, it is moved here --> https://hastebin.com/kuvuwivale
The bot didn't warn you for no reason, now you edited the wall of text back in
[Rule #6](#rules message): Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
For sharing code or logs use https://dpaste.org/ (pick YAML for the language) or https://www.codepile.net/ (pick YAML for the language).
You are using an average filter on an empty list
That's where this error comes from fmean requires at least one data point
What is the best way to do math a math operation based on values received by multiple sensors and then pushed back out to a new sensor?
I assume a template sensor, but I am having some trouble doing the kind of operations I want to within the constraints of my understanding of Jinja templates. Namely setting the value of a variable to the value of one sensor and then using that variable in a function
{% set val = sensor_id %}
sensor_id being one of state... options explained in templating docs
Template preview in dev tools is your best friend here
Thank you that helps a lot. I had the set in the wrong place. Still getting a "unknown tag low_temp. was looking for elif, else, or endif"
{% for i in range(1,24) %}
{% if (state_attr('weather.openweathermap', 'forecast')[i].temperature) <= low_temp %}
{% low_temp = (state_attr('weather.openweathermap', 'forecast')[i].temperature) %}
{% endif %}
{% endfor %}```
oof dumb
Thank you
Not sure why you reuse the same variable name
I am trying to find the lowest in an array of 20
So I need a starting value (index 1) and then if there is something lower, set low_temp to the value of that index, and if its not, keep checking
Hmm... yeah that just returns the value of index 1
{% for i in range(1,24) %}
{% if ((state_attr('weather.openweathermap', 'forecast')[i].temperature) <= low_temp) %}
{% set low_temp = (state_attr('weather.openweathermap', 'forecast')[i].temperature) %}
{% endif %}
{% endfor %}
{{ low_temp }}```
I usually run some "debugging prints" by displaying values mid function to see what happens
Alright yeah adding some prints shows that the value is set properly in the if statement, but is not returned outside of the if statement. If I print low_temp inside the for statement before the if, its just always equal to index 1
Okay this doesnt work in python either so I am clearly goofing up
the problem is the for loop. You need to use a namespace to access a variable you set within the loop outside it
something like:
{% set ns = namespace(low_temp = 0 %}
...
{% set ns.low_temp = xxx %}
...
{{ ns.low_temp }}
This worked in the template editor. Thank you!!
Just to confirm, the following will just return the value of ns.low_temp to the template sensor correct?
value_template: " {% set ns = namespace(low_temp = 0) %}
{% set ns.low_temp = (state_attr('weather.openweathermap', 'forecast')[1].temperature) %}
{% for i in range(1,24) %}
{% if ((state_attr('weather.openweathermap', 'forecast')[i].temperature) <= ns.low_temp) %}
{% set ns.low_temp = (state_attr('weather.openweathermap', 'forecast')[i].temperature) %}
{% endif %}
{% endfor %}
{{ ns.low_temp }} "```
@opaque marlin Yes, but with a template like that I would use the multi line format
forecast_low:
value_template: >
{% set ns = namespace(low_temp = 0) %}
{% set ns.low_temp = (state_attr('weather.openweathermap', 'forecast')[1].temperature) %}
{% for i in range(1,24) %}
{% if ((state_attr('weather.openweathermap', 'forecast')[i].temperature) <= ns.low_temp) %}
{% set ns.low_temp = (state_attr('weather.openweathermap', 'forecast')[i].temperature) %}
{% endif %}
{% endfor %}
{{ ns.low_temp }}
I would also change it a bit:
forecast_low:
value_template: >
{% set ns = namespace(low_temp = 0) %}
{% for item in state_attr('weather.openweathermap', 'forecast') %}
{% if loop.first or item.temperature) <= ns.low_temp %}
{% set ns.low_temp = item.temperature) %}
{% endif %}
{% endfor %}
{{ ns.low_temp }}
On second thought, you could use simply this:
{{ state_attr('weather.openweathermap', 'forecast') | map(attribute='temperature') | min }} }}
Hi. Can someone say, whats wrong with this code?
- name: "Wetterstation Solarspannung" unique_id: "wetterstation_solarspannung" unit_of_measurement: "V" icon: mdi:solar-power state: "{% if state_attr('sensor.0x00124b000cb0d756_l1', 'device_l1') == "40-01" %} {{ state_attr('sensor.0x00124b000cb0d756_l1', 'voltage_l1') }}" {% endif %}
Many things
state: >
{% if state_attr('sensor.0x00124b000cb0d756_l1', 'device_l1') == "40-01" %}
{{ state_attr('sensor.0x00124b000cb0d756_l1', 'voltage_l1') }}
{% else %}
What do you want here? When device l1 is not 40-01
{% endif %}
Thank you. I‘ll try that. 😄
Okay. The code works now, but my idea how to differentiate two values on the same attribute wont.
i have a script i use to turn on random lights. After the script runs, i use this to tell me which lights are on:
{{ dict((states|selectattr('entity_id', 'in', state_attr('group.inside_switch_card_2', 'entity_id')))|groupby('state'))['on']|map(attribute='name')|list }}
i have a similar script that turns lights off and a similar notification that tells me which lights are on. if all the lights are off, i get a template error. Is there any way in a script to tell which lights were recently turned off? Like a trigger to state for scripts?
Remove the dict and groupby, use selectattr instead
Actually, that whole thing is poorly optimized and it’s throttled to 1 update per minute
{{ expand('group.inside_switch_card_2') | selectattr('state', 'eq', 'on') | map(attribute='name') | list }}```
auh, thanks for that.
{{ expand('group.inside_switch_card_2') | selectattr('trigger.to.state', 'eq', 'off') | map(attribute='name') | list }}
so would that work?
That would return the name of all entities in that group which have the state off
Wait, you need to change trigger.to.state with 'state:
You can replace 'off' with trigger.to_state.state if that is what you want
trying to fix this issue
{{ expand('group.inside_switch_card_2') | selectattr('state', 'eq', 'trigger.to.state.state') | map(attribute='name') | list }}
Don't quote variables
so no quotes around trigger.to.state.state ?
here again, because my automation question was better suited here (sry for missposting in wrong channel :()
I have a variable that contains time with seconds and I want to get rid of the seconds => 1:50:32 should be 1:50 only
How can I do that with my automation that got a notification with {{ states('sensor.time_remaining') }} ?
as I was saying in #automations-archived
Trying to increment the value of a sensor in a bulb's brightness
I did a template like this:
brightness: >- {{states.light.luz_balcao.attributes.brightness + int(states('sensor.tuyaknob_action_step_size'), 0)}}
but it still doesnt work, I think the issue is that the value sensor.tuyaknob_action_step_size is back to None by the time the service runs.
So I guess I need to retain the value somewhere?
{{ "1:50:32"[0:-3] }} -> 1:50
yup, that is the issue, I set the automation to send me a message with the sensor value and it is Always none.
I need to figure out how to retain the value
I think I had an idea
I will create another sensor that retains its the value of other one as long as the value is not none
sensor:
- platform: template
sensors:
knob_last_step_size:
friendly_name: "TuyaKnob Last Step"
value_template: "{{ state_attr('sensor.tuyaknob_action_step_size', 'action step size') not in ['None'] }}"
I think this is the way
ah this is returning a boolean uhhhh
What do I have to return in the value_tempalte so that the value is ignored
ty! working like charm! ❤️
I'm new to template switches. Can I just start using them in my button-card or do I need to do something to enable them elsewhere first?
I see in the documentation that something needs to be added to configuration.yaml but it looks very specific.
This:
I see in the documentation that something needs to be added to configuration.yaml but it looks very specific.
Do I add that for every template switch I create?
I would suggest to create a trigger based template sensor, trigger on state changes of the source sensor.
Then check if it is a wanted state, and if so, use trigger.to_state.state, else use this.state
"{{ is_state('sensor.skylight', 'on') }}"
This is the part that confuses me. That suggests to me that the template is only applicable when the entity is on. Is that correct?
No, it's defining the state of the switch
Of the template switch, not the switch of the device, right?
Okay. And sensor.skylight is the actual device?
That's the one in the example of the documentation.
I'm using my motion sensor for this.
So I thought it would be switch.hue_motion_sensor instead.
Your motion sensor is unlikely to be a switch
I'm using it's on/off state for detecting motion.
Still not a switch
What would it be?
What is it?
I suppose I can find out.
Yes
Let me look.
I can't upload the image here.
But under configuration, there is a switch called Motion.
And it's entity ID is switch.hue_outdoor_motion_sensor_1_motion
When I turn it off, my motion sensor won't detect motion.
And that's what I'm turning on and off in my button-card.
ok
so it's not actually an indication of whether the motion sensor is detecting motion, but whether or not it should be active
what would be the correct syntax for this be? entity_id: "input_number.{{ area_id(trigger.entity_id) }}_light" as that doesnt seem to work
action:
- service: input_number.set_value
data:
value: "{% if is_state(trigger.entity_id, 'on') %}128{% else %}0{% endif %}"
target:
entity_id: input_number.{{ area_id(trigger.entity_id) }}_light
it doesnt set the number on the entity
Correct. The point of this will be to turn the motion sensors back on after 30 minutes of being turned off by the button-card.
you're adding "input_number." onto a full entity_id that probably already contains it, but you're still only providing a partial snippet of your autiomation
more guessing
it's not, I'm wrong
I suspect that you don't actually want "area_id" there, which is some long random string
you probably wanted "area_name"
No, if you've set up your areas less then maybe a year ago, they are actually meaningful
is the result of area_id not the lower cased version of area_name? as it works when passing it into my script that takes the area_id in the format of kitchen living_room etc
Slugified versions of the name
ok, mine aren't
They used to be random ids like device ids
{{ area_id('switch.fr_reading_lamp') }} -> e195927a039b4c2fa712c58b864daf4b
I recreated them because of that
but I probably set them up a while ago
What does the trace show?
Yes, with none as area_id
Looks like the motion sensor is not added to the area
"entity_id": [
"input_number.none_light"
]
Is there a way to modify the configuration.yaml file from the Home Assistant web interface?
Depends, if you are running HA OS, you can install #add-ons-archived for that
I use the Studio Code Server addon
Can you get that from HACS?
no, HACS has nothign to do with addons
The alternative is to just access it via Terminal, I suppose?
You can use VSCode and create a connection using ssh
I have HAAS running inside a docker container on Unraid.
But all of this is offtopic here, maybe something for #general-archived
Is what he's covering in this video the same as a template switch?
https://www.youtube.com/watch?v=GnW0mLt2YLg
Since I don't know much about them, I figured this might be helpful.
Okay, that helps to visualize.
So turn_on: is indicating what happens if I turn on that switch?
And turn_off: the inverse.
yes
Or instead of turning the switch on via my button-card, I call this template?
which is a switch
So whatever the switch is named, I call that switch and turn it either on or off?
use the toggle action
There it is with toggle.
I noticed that the color doesn't actually change anymore based on state (but it does stay blue for on).
Should I tie the state to the actual device switch?
the switch should already do that
Hmm, let me check again.
that was the whole previous discussion
I might have done something wrong then.
I checked the log book and it's not actually toggling the device or setting the datetime.
was the switch created? did you actually create the input_datetime?
that was more than needed, but the questions remain
and it sounds like you didn't check your config first, either
The input_datetime needs to be created as a helper?
yes
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
- HAOS & Supervised use
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
BTW, there was an automation in there as well, so if you just slapped the whole thing in configuration.yaml, that won't go well
Nah I only put the switch lol
Okay, that fixed the datetime issue.
It is not changing the state of the switch, though.
oh, I missed that
I think I need to add that as part of the turn_on and turn_off, right?
the turn_off part
turn_off:
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.motion_sensor_on
data:
datetime: "{{ now() + timedelta(minutes=30) }}"
- service: switch.turn_off
entity_id: switch.hue_outdoor_motion_sensor_1_motion
for the turn_on part, I'm just setting the input_datetime to 1 second in the future and let the automation do it
The automation is giving me an error: "Message malformed: extra keys not allowed @ data['entity_id']"
alias: Front Patio (L) Motion Sensor On
trigger:
platform: time
entity_id: input_datetime.family_room_l_motion_on
condition: []
action:
service: switch.turn_on
entity_id: switch.hue_outdoor_motion_sensor_1_motion
oh, my fault. the trigger should use "at:"
trigger:
platform: time
at: input_datetime.family_room_l_motion_on
@inner mesa Awesome! It works. Thank you so much for all of your help.
It's nice to actually understand how this functions now.
I'll try my hand at the input_boolean as well so that it doesn't run twice when I manually turn it back on.
yeah, that's a bit of a hack. You don't want the automation to run in 30 mins if you already turned it on, mainly because you could have turned it off outside of HA and want it to stay that way
you could set the input_datetime in the past (1 second, 1 minute, whatever)
and then just turn it on in the turn_on: part
that's easier than maintaining a helper
only one way to find out
Ah, it is. Thank you!
@inner mesa It looks like I actually don't need to make any modifications.
If I turn it off, turn it back on, then turn it off again, it waits the full duration before turning it on again.
It doesn't just wait the time from the first turn off.
right, there was nothing wrong with what I provided
Oh, silly me.
you just didn't like it 🙂
No, I do haha. I just didn't realize it would work that way.
I was under the impression that once the automation was triggered, you'd have to expressly stop it.
But now I'm realizing the automation doesn't trigger until the datetime reaches the stated time.
there's nothing there that keeps running
So if you change it midway, the automation never ran to begin with.
So it'll just keep delaying it's start.
Yeah, okay.
Woo! Thank you so much for all the learning lol
This'll be really helpful when I go to create other automations.
@inner mesa I've duplicated the first template for the other two. Now I'm having a strange issue. One of the copies I made worked, the other wasn't showing up as a switch. Then I tried commenting out the one that worked, and it was still working.
I restarted Home Assistant each time.
No idea
Sounds like you have a formatting issue, and I suspect that HA didn't actually restart because of it
Oh
YAML file /config/configuration.yaml contains duplicate key "switch". Check lines 18 and 58
I thought switch: was generic.
You can only have and only need one switch:
hi to all, someone can help me with a variable? in a script i'm declaring a variable with value retrieved from a state (alexa volume level, decimal value between 0 and 1)
in script trace, i see variable's value sets right, but when i call variable, to re-set alexa's volume to variable's value, it's looking for a float value, and it's not working
i try to post just few lines there
the error is " Error rendering data template: AttributeError: 'float' object has no attribute 'lower'"
(now is different, proablyy due to contrent tryes!
variable's value seems ok
@still surge Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
still trying to figure out how i can change this from all the lights that are on to lights that just turned off
message: "Random light turned off - {{ expand('group.inside_switch_card_2') | selectattr('state', 'eq', 'on') | map(attribute='name') | list }}"
in a script so it doesnt have a trigger
Howdy 🙂
something like last_changed <= 5
this is very interesting - what am I not seeing here?
{% set d=expand(integration_entities('plex'))|selectattr('state', 'in', ['playing', 'paused'])%}
{{ d|list|count }}
{{ d|list|count }}
The output is:
1
0
Hello,
I've got this template which gets the three cheapest hours of electricity from the sensor. The sensor have an attribute with raw_today: which have value. This works fine! There's also raw_tomorrow in the sensor which i would like to include in this. How would i add it?
value_template: >-
{% set l=state_attr('sensor.nordpool', 'raw_today')|sort(attribute='value') %}
{{ (now() >= l[0].start and now() <= l[0].end)
or (now() >= l[1].start and now() <= l[1].end)
or (now() >= l[2].start and now() <= l[2].end) }}
I figured it out
Something like |selectattr('last_changed', 'gt', now() - timedelta(minutes=5))
Pfft
How do you want to account for the 3 cheapest hours tomorrow? Because the 3 cheapest hours today may not be the same as those tomorrow.
Exactly, that's why i want the sensor. Currently it's "false" or "true" and that's enough to turn on charging of stuff during the cheapest hours. Ultimately i would want the cheapest hours from 20.00 to 07.00 or something like that.
Ah so try concatenating the raw_today and raw_tomorrow lists, and then sort the resulting concatenated list. Should be able to do it with something like set l = (state_attr('sensor.nordpool','raw_today') + state_attr('sensor.nordpool','raw_tomorrow'))
Exactly! I tried that and it sorts the values but only per day. So raw_tomorrow sorts by itself and raw_today sorts by itself, not combined.
Hi, I have this template, which I want to send to mobile when leaving. How to make "normal" text from it?
@winter cape posted a code wall, it is moved here --> https://hastebin.com/qimahuraxa
In Developer tool it looks like that, but I would like: Pere pračka or Běží myčka a pere pračka or 4 okna jsou otevřena, pere pračka a běží myčka....
`4 okna jsou otevřena
běží myčka
pere pračka`
So you want 'elif'?
Yes, I need only information what is on...
You just have a sequence of if statements
And is another way how to do it?
On.... when I hold switch, television, pc and other goes to off. This I need only for information - about windows, dishwasher.... which is usually not a problem when its on
then why are you checking if they're off?
oh, sorry, its only for test in developer tools.. normally is in template on
Yours will actually prob work better
I had just finished arduously typing that on my phone when you said "nevermind!" 🙂
I'm not really following what's wrong with the current output and what you want it to be
with your logic, if they're all "off", it will print all three
what did you want?
its a script that just randomly turns off lights while we are on vacation. just trying to get notifications of whats going on to confirm things are working
in the beginning imwas showing lights on after i turned one off, but if they are all off it would error
I would like to have a normal sentence. With a capital letter at the beginning, with a dot at the end.
since I can't read whatever language that is, it's hard for me to figure out what you want
but again, I've described what your logic will do. What do you actually want?
do you want it to print all three if all are "off"? Only some of them?
Understand 🙂 sorry.... now its look like 4 windows are open dishwasher is on washing machine is on
and... what do you want?
I want to print .... 4 windows are open (if are) and dishwasher is on. ( if is ).... or Dishwasher is on, washing machine is on and ......
I dont have problem with sensors, only with format of print
making these things grammatically correct is challenging and very language-specific
you seem to have a command of "if" statements, so you construct it with that
Understand.... template is in my local language, its not problem.... only with capital letters at the begin , dot at the end...
its variable
TypeError: 'datetime.timedelta' object is not iterable
I think you're going to need to figure this out
this is an example in English:
{% set data = ["foo", "bar"] %}
{% if data|length < 3 %}
{{ data|join(' and ') }}
{% else %}
{{ data[:-1]|join(', ') }}, and {{ data[-1] }}
{% endif %}
Thanks, I'll give it a try.
better:
{% set data = ['foo', 'bar'] %}
{{ data[0]|title }}
{%- if data|length < 3 -%}
{{ ' and ' ~ data[1] }}
{%- else -%}
{{ ', ' ~ data[1:-1]|join(', ') }}, and {{ data[-1] }}
{%- endif -%}
.
this is just an exercise in playing with it in the template editor until you get what you want
alright, I'm done with this: https://dpaste.org/ZzDvu
this works well enough for me
but I dont know how to add data/list from my sensors....
Ok, thank you
To get the timeframe i want maybe i need to throw the wanted strings from the array into a new variable and then sort that for the lowest price...?
is there a simple filter to turn f.e. "Name With Spaces" into name_with_spaces or is lower and replace the only way?
|slugify
Or maybe even better. How could i select [2] to [8] here?
[2:8]
Aah, thanks
I think i got it. I'm sorry if it's horrible :P. This get the five cheapest hours between 20:00 and 07:00 (rows 20:31).
value_template: >-
{% set l=state_attr('sensor.nordpool_kwh_se3_sek_3_10_025', 'raw_today') %}
{% set g=state_attr('sensor.nordpool_kwh_se3_sek_3_10_025', 'raw_tomorrow') %}
{% set v = l + g %}
{% set h = v[20:31] | sort(attribute='value')%}
{{ (now() >= h[0].start and now() <= h[0].end)
or (now() >= h[1].start and now() <= h[1].end)
or (now() >= h[2].start and now() <= h[2].end)
or (now() >= h[3].start and now() <= h[3].end)
or (now() >= h[4].start and now() <= h[4].end)}}
Coming back to this old conversation since my solution wasn't working. My understanding currently is that availability templates make sure the sensor goes unavailble when the original sensor goes unavailable, which is not what I want. I want my template sensor to be the last known value before the original sensor went unavailable.
At this point I'm almost starting to think what I would like to do is impossible
Although it seems like it should be so simple lol
I would suggest to create a trigger based template sensor, trigger on state changes of the source sensor.
Then check if it is a wanted state, and if so, use trigger.to_state.state, else use this.state
- name: Occupied (Bedroom)
device_class: presence
state: >
{{
is_state('binary_sensor.motion_bedroom', 'on') or
(now() - states.motion_bedroom.last_changed).seconds < 5
}}
icon: >
{% if is_state('binary_sensor.occupied_bedroom', 'on') %}mdi:bed-queen{% else %}mdi:bed-queen-outline{% endif %}
Can anyone see anything wrong with this? developer tools shows as unavailable, my one for the living room which is almost identical shows as on but kitchen and hallway also show unavailable all pretty much identical, the only real difference is I am in the living room currently
You are missing binary_sensor in the second part of the template
states.binary_sensor.motion_whatever.last_changed
Yep that was it, thanks
The 5 seconds probably won't work reliable though, it will be anything between 5 seconds and 1 minute, as now() will be updated one per minute
remove that and replace with delay_off i imagine is the better solution
Yep
So I just found out there's a new, modern template setup and I want to start to transition over to it, but I can't get an attribute setup correctly. This displays the attribute, but the value is "null". https://hastebin.com/ulugugatin.less
It sounds like one or both of the entities is not a number
You should use states(): https://www.home-assistant.io/docs/configuration/templating/#states
Seems you indeed missed the new, modern template to get a state
And specify defaults
(which was introduced before I started using templates)
It was carved on a stone tablet discovered around 2017
Ah, that's even before I started to use Home Assistant (well at least the attempt that succeeded)
Instead of rounding to 0 digits in combination with floor you can also do an integer division
@chilly locust here you go
template:
- sensor:
- name: "Pregnancy Week New"
unit_of_measurement: "weeks"
state: "{{ states('sensor.pregnancy_days') | int // 7 }}"
availability: "{{ states('sensor.pregnancy_days') | is_number }}"
attributes:
days_in_week: "{{ states('sensor.pregnancy_days') | int) % 7 }}"
@young lake https://yaml-multiline.info/
My brain is too fried from the day, but this page should have the answers for your multi-line issue
Thanks, mate.
Looking for help with a template variable in an automation.
I've played around with several iterations of this but I can't figure out why I'm getting an error.
This seems to be the problematic code:
notification_message: >-
"{% if is_state_attr('trigger.to_state.entity_id','friendly_name')%}
{% state_attr('trigger.to_state.entity_id','friendly_name') %}
{% else %}
Walter
{% endif %}
is in range!"
Now I think they need to name the baby after you...
It throw the error: "expecting an 'else', 'elif', or 'endif' for the line with state_attr in it.
Is there another way to template the return value for the if statement?
when creating a binary sensor can you define the area directly? instead of assigning a unique id then changing it in the gui? cant find any documentation on it
I don't think so
Thats sucky, thanks
Could someone lambast me for what's wrong with my code posted above? I know it is something obvious, I just can't see it. A good tongue lashing would go a long way at this point. 😄
Update from using the template editor:
This seems to be correct syntatically:
"{% if is_state_attr('trigger.to_state.entity_id','friendly_name') %}
{{ state_attr('trigger.to_state.entity_id','friendly_name') }}
{% else %}
Walter
{% endif %}
is in range!"
But the if conditional statement throws the following error:
TypeError: is_state_attr() missing 1 required positional argument: 'value'
there are many things wrong with it
first, you're surrounding the thing in quotes. remove them
second, you're surrounding the variables in quotes (like trigger.to_state.state). remove them
third, you need to indent your template
fourth, is_state_attr() takes three parameters and you've only provided 2
there may be more
Beautiful! Thank you!
My wife says no, but I'll add it to the list 😉 Thanks!
Can anyone suggest a working template to determin if someone came in or out a front door? example, front entry door and screen door opens. then entry door closes, then screen door closes.
I was plaing around with someting like this but cant seem to get it to work.
value_template: >
{% if ((states.binary_sensor.f_e_d.last_changed) > ((states.binary_sensor.f_e_d.last_changed) and is_state('binary_sensor.f_s_d', 'on')) %}
((states.binary_sensor.f_e_d.last_changed) and is_state('binary_sensor.f_s_d', 'on')) would resolve to a datetime then an and statement to a true/false outcome. Are you meaning to collect the the two last_changed states as a a true/false outcome and use an and statement to the is_state?
Well I'm completely stuck. I can't get any new template to work at all now. I even straight-up copied the temperature example from the online documentation, only changing to my sensor names, and it still doesn't work. The issue is they don't even exist, no matter how many restarts I do or different browsers I use. I've tried putting them directly in the configuration.yaml file in case my !include wasn't working, but no luck either. Thoughts on where I should start?
~share what isn't working
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
and you didn't mention checking your config
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
- HAOS & Supervised use
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
Verifying my config always comes back clean.
https://hastebin.com/eduzasakas.yaml
it looks fine to me
there's really not much to it
you're missing a ( in the attribute
I just stuck your code in my file and tried to reload templates. It immediately gave me an error message in the log
you can just remove the ')', as it's not needed
in short, when things don't work, review your log
And reload templates from
-> YAML, don't restart HA over and over again. The former will tell you what's wrong without preventing HA from restarting or starting at all
You're kidding right? A single parentheses was the whole reason none of them have been working? Funny enough, that's a common theme with me sometimes. Everything's perfect except I miss a single punctuation somewhere and screws everything up.
I added that missing parentheses and all 3 of them show up now. Thank you!!!
the template loader bails when it hits something it doesn't like and then doesn't load anything
Good to know!
you can just remove the ) you have there as you don't need it
| has the tightest binding
anyone see what's wrong with this? https://pastebin.com/pi620EnS, trace: https://pastebin.com/gShRYGim the condition is failing, and doesn't look like it's transforming things
Yes, this part is all messed up:
is_state("input_boolean.override_light_{{ area_id(trigger.entity_id) }}",
'off')
hey guys; i have around 20 Sensors in which i want to display an attr for.
Example: sensor.front_keypad_info - i want to display attr linkQuality - so i did this
{{ state_attr('sensor.front_keypad_info', 'linkQuality') }}
and this works for the one; but what would be an easier way to get this for all 2 sensors?
I could be going at it the wrong way. but I have a contact sensor on my front door, front screen door and a motion sensor outside. I would like for the house to know if someone walked outside as to leave. steps. (front door opens), ( then screen door opens), (then front door closes), (then screen door closes) I am not sure where a motion sensor could fal l into this.
there are times that i travel and i have guest come over to let out my dogs. I cant seem to get them to arm my house when they leave. I have dogs in the house or i would use the lack of motion in the house.
I you put each of those entities in their own {{ }} in the template developer tool, you'll be able to see what they are being returned as and what the outcome of those operators are. It helps me to work through the logic that way.
I was trying that but i am vary new to templatiing.
I also find it helpful if the logic is complicated, to built a binary sensor that be complexed then build my automation from that sensor, where you can introduce time delays and conditions etc.
Thats what i am hopoing to do.
I have done it to others but i cant seem to get it to work correctly for this.
- platform: template
sensors:
sleep_stage_3:
friendly_name: "Sleep Stage 3"
device_class: motion
value_template: >-
{{ as_timestamp(states.binary_sensor.bed_motion.last_changed) < as_timestamp(states.binary_sensor.sleep_stage_2.last_changed) }}
{{states.binary_sensor.f_e_d.last_changed}}
{{states.binary_sensor.f_e_d.last_changed}}
{{is_state('binary_sensor.f_s_d', 'on')}}
start with these separately then work at introducing operators to see what they do. The two links on the template developer page for the templating documentation and jinja are hugely valuable.
I'm also really new to templating so I'm not the right person to tell you the best way to achieve something but can definitely tell you what I've found helpful to get things working for myself.
Thank you vary much.
also very helpful to post code here between ` symbol so it formats correctly. Or use 3x of them to mark the start/end of a code block.
Will do, thank you.
What would the correct syntax be?
@worn cloud posted a code wall, it is moved here --> https://hastebin.com/zefijemape
Hello; I have the following template that gets the attr from a group of sensors
{% set zwave_link = expand('group.ringallsensorsinfo') %}
{% for link in zwave_link | sort(attribute="attributes.linkQuality") %}
{{
{
'Name': state_attr(link.entity_id,"friendly_name"),
'Link': state_attr(link.entity_id,"linkQuality")
}
}}
{% endfor %}
it outputs like this:
{'Name': '1st Flr Carbon Monoxide Info', 'Link': 'ok'}
{'Name': '1st Flr Smoke Alarm Info', 'Link': 'ok'}
How would i convert this to JSON so i can pick out the value Link and set an automation if it ever says Bad to send me an alert?
Where are you using this template?
i am currently just using it under Developer Tools
later i would like to extract the json link value and if it says bad then do something
You could put it in a template sensor attribute, but not like you are doing now, you'll have to use a namespace then
{% set ns = namespace(zwave=[]) %}
{% set zwave_link = expand('group.ringallsensorsinfo') %}
{% for link in zwave_link | sort(attribute="attributes.linkQuality") %}
{% set ns.zwave = ns.zwave + [
{
'Name': state_attr(link.entity_id,"friendly_name"),
'Link': state_attr(link.entity_id,"linkQuality")
}]
%}
{% endfor %}
{{ ns.zwave }}
That's something for #frontend-archived
my bad, but i worked it out now thank you
This may be the wrong place, but it is a template i think
template:
sensor:
name: "Electricity Live Usage"
unit_of_measurement: "W"
state_class: measurement
device_class: power
state: "{{ (states('sensor.frient_energy_monitor_power_meter')|float * 1000 / 800) | round(2) }}"
name: "Electricity Usage Total"
unit_of_measurement: kWh
state_class: total_increasing
device_class: energy
state: "{{ (states('sensor.frient_energy_monitor_energy_meter')|float * 1000 / 800) | round(2) }}"
Ive got this to translate some data from an energy reading device thingy
the "Usage Total" sensor is present, however the live usage, doesnt seem to appear,
nor does the validate check in YAML suggest that there is an issue?
but when i search in states its not present
ignore the quotes or lack of quotes around the unit of measurements, purely testing to see if that was the issue
You need to make it a list, every sensor needs to be a list item:
template:
- sensor:
- name: foo
state: "{{ template }}"
- name: bar
state: "{{ other template }}"
Note the dashes (-) before each sensor, but also before sensor:
yeah i tried this before but it didnt seem to like it in the least... let me try again
thats done it!
i think i was missing the spaces between - and sensor
super thanks
so im guessing without the - and proper notation it iterates and just generates the last one in the list
If you don't provide it, and a list is expected, it will covert it to a list item itself, but in your case that caused duplicate keys
Anyone see what's wrong with this? https://pastebin.com/pi620EnS, trace: https://pastebin.com/gShRYGim the condition is obviously erroneous but not sure how to fix
{{ is_state('input_boolean.override_light_' ~ area_id(trigger.entity_id), 'off') }}
I did have {{ }} around it originally didnt know about the ~ syntax will give that a go, thanks
That will concatenate both sides of it as strings
You can't have {{ ... }} inside {% ... %}
if you just want it for display, don't make template sensors, just display the attribute in the entities card.
can someome please give me a hint what i am missing? i got two mqtt sensors which are deliviering current power use and the current count of my smartmeter. using mqtt browser i get this information:
{
"timestamp": 1661859022456,
"value": 8744725.700000001
}
then i created a template sensor:
mqtt:
sensor:
- name: "Aktueller Stromverbrauch"
state_topic: "vzlogger/data/chn0/raw"
device_class: power
unit_of_measurement: "W"
value_template: "{{ value | float}}"
but i am not getting a value until i disable #value_template
:/
that should be it
{ "timestamp": 1661859127458, "value": 8744738.5 }
don't need the float either
yep, thats all
"{{ value_json.value }}"
but i could divide the value
right?
the count is 8744
the value is coming out with a wrong format
yeah then just / 1000
alright will check
thank you so far
🙂
value_template: "{{ value_json.value / 1000 }}"
like that i guess? 🙂
or do i need to create another sensor which divides the value?
nope, thats good
could you give me one more hint how to split / cut the value? currently i get: 8.746,0645 kWh but i only want 8.746,06... my sensor currently looks like:
- platform: mqtt
name: "Aktueller Zählerstand"
state_topic: "vzlogger/data/chn1/raw"
device_class: power
unit_of_measurement: "kWh"
value_template: "{{ value_json.value / 1000 | int | round(2)}}"
or even 8746 would be more than fine, without any decimals
put parenthesis around the math portion. right now you're only rounding the denominator
And you're rounding an int
{{ (333333.3334,31 / 1000) | float | round(2)}}
ValueError: Template error: float got invalid input '(333333.3334, 0.031)' when rendering template '{{ (333333.3334,31 / 1000) | float | round(2)}}' but no default was specified
i think the combination of . , is bad
Correct, the decimal symbol is . (dot), not , (comma)
It's now treated as a tuple
Do you need the bit after the comma? If not, you can split the string on the comma, take the 0th part and cast that to float to subsequently do your math on.
Then you need not bother with the math.
{{ '12345.678,9012'.split('.')[0] }} gives 12345
Assuming of course that the mqtt output is a string.
value_template: "{{ (value_json.value.split('.')[0] / 1000)}}"
trying something like this
https://prnt.sc/1ouPlRiX9ZDY thats what i get via mqtt, screenshot is from mqtt browser
and what value from that would you like to display?
the one behind "value", should look like: 8746
i understand that part but what number would you like to see from that value_
{{ (value_json.value / 1000) | int }}
{{ (value_json.value / 1000) | round }}
pick one
The value from mqtt uses a . Your sensor is outputting in your front end based on the settings on your user.
Why different countries use the same characters for exactly opposite things is baffling
Basically, what I’m saying is you’re incorrectly testing the template in the template editor
You need to take the value that's under the hood when testing. I.e. developer tools -> states page, use that value.
do not copy values from the front end to test in the template editor
so to recap, this is what's coming from your mqtt:
{ "timestamp": 1661859127458, "value": 8744738.5 }
And that's the number you should be testing with. Notice the lack of commas, and the presence of a period.
{{ (value_json.value / 1000) | round(2)}}
and for your testing...
{{ (8744738.5 / 1000) | round(2) }}
Yeah got this so far
But i feel like my Split Statement is wrong allthough i am using the dot
🤷♂️
He just needed parenthesis and he's now down this rabbit hole of wrong thinking.
@noble pawn read my responses.
starting here
Will Do and get back, Thank you Very much!
Hey crew,
Is filtering (like lowpass) available in templates? Or do I need to build a new sensor?
it's not, you have to build a new sensor
if you're just looking at the previous point, you can use the this variable to get the previous state before calculating the new state. Anything beyond that and you need to use the lowpass filter
do my own exponential filter with this is what you mean?
use this.state to get the previous state. Then filter or not. That's what I mean. But you can't get historical data, so anything beyond 1 state would need to be spooled in your attributes (and wiped out on restart) or using one of the many integrations that looks at your history.
(and wiped out on restart)
apparently if you give the sensor aunique_id, they're retained
so I'm told
great - Thanks for the help. As long as I can get the previous value, I can math it - Sort alike... the new value's weight level, layered on the old value
So you don't' have to build up the whole time series
I don't think attributes are tho, are they? That's what I mean by wiped out and spooled. You'd have to spool a list of old data instead of using history.
I haven't tried it, but I think TheFes mentioned that they are, and I just believed it. It's all part of the state
Hi. i have a sensor that outpots true or false. I would like it to replace true with Low and false with High. How can this be done?
with a simple template sensor, but it depends on whether entity state in HA is really the string "true" or "false"
its from this code:
- platform: template
sensors:
nordpool_highlow:
friendly_name: Nordpool High Low
value_template: "{{ (states('sensor.nordpool_diff_rank_20') | float ) > 0.8 }}"
change the value_template line to this:
value_template: "{{ iif(states('sensor.nordpool_diff_rank_20')|float > 0.8, 'Low', 'High') }}"
For trigger based template sensors attributes are retained as well
is there a method of setting the value of a helper such as an input_number but in such a manner that it won't cause it to trigger an automation that relies on it?
and realise that's probably a better question for #automations-archived
no, but I'm pretty sure this is a xy problem
maybe you can elaborate on what you're actually trying to do
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.
Basically i have an input_number helper for every room to manually set the brightness of the light or other automations will automatically set the input_number so that it keeps track of desired brightness and stops automations accidentally setting one value over another.
This then triggers another automation to run a script that sets all lights brightness for that area to the value of the input_number
I want to make sure not to create a loop if i create an automation that syncs the input_number to the brightness just incase the brightness was different such as directly changing the light entity brightness or if it changes itself due to being turned off and on again at the swtich, etc
i suppose i could just add a condition to every automation that is triggered by them to stop if there's no difference between brightness and helper
what do you mean, manually set the light?
@worn cloud posted a code wall, it is moved here --> https://hastebin.com/uhecasuvoh
I'm just curious as to why this is even an automation, you could just make a template number instead of input_number, then it would only fire when you manually set it through the service.
Thank you ; I placed this into a template sensor but its not outputing anything
What does it return in
> templates
You should use it as an attribute, not as the state
welll seeing that no zwave device has linkQuality as an attribute, i would assume that's always empty
Looks like it's some Ring sensors
I got pretty much everything transitioned to the new template format, but now one of my sensors is being finicky again. Even the old code won't calculate it correctly. Essentially, the attribute needs to determine what day of the week it is and display it as a number (0-6). For me, Wednesday is Day 0, Tuesday is Day 6. Thoughts on this? Here is the full code for that, focusing on the pregnancy_weeks sensor & attribute.
https://hastebin.com/jafabomece.pl
alot of those templates are mish mashing date times when they don't need to
TBH, it was someone else who wrote those that I added on to. How would you recommend updating them?
Chrome keeps crashing on that link on my mobile
Try this? https://hastebin.com/raw/jafabomece
{{ state_attr('calendar.baby_tengowski', 'start_time') | timestamp_custom('%-I:%M%p on %a, %B %d') }}
{{ (now() - states('input_datetime.pregnancy_last_period') | as_datetime | as_local).days }}
{{ (states('input_datetime.pregnancy_due_date') | as_datetime | as_local - now()).days }}
first 3
days_in_week: "{{ states('sensor.pregnancy_days') | int % 7 }}"
unless you want it days from monday, then it's different
but if you want it day in the week from the pregnancy date
That's what I provided yesterday, he seems to have added the -1
The weekday is relative to the day in the week. Wednesday is our Day 0.
Yea otherwise it would be Day 1-7. I need Day 0-6.
that's not how % works
% 7 will never hit the number 7
it will be 0 through 6 only
You will now end up with -1 to 5
Ahh that makes sense. I thought % was just a fancy /.
so if you have 10 and you mod it with 7, you'll get 3
if you have 7 and you mod it with 7, you'll get 0
And 17 % 7 will be 3 as well
right
basically, it returns the remainder
divide by this number and return the left over amount
that's probably a better explanation
So that fixes the attribute, but the state is now quite a large number (16.8571428571429). Just need it to be 16. I think that's why rounded it to 0 with the floor.
You changed // to /
Is this another change that he made?
// is an int division, it's different than /. // will divide a number a return only the whole number.
@chilly locust lol, it's better to not fix typo's from thefes
cause they aren't typos 🤣
Maybe I should have explained it as well 😛
Yeah I've realized that today. I should've just trusted you guys. Hahaha
directly set the device rather than letting my automations do it via the helper
The Ring MQTT admin includes a linkQuality attr for each sensor that says ok or bad
right, i get that but you're using the helper to set the lights right?
and have the automation run off the helper
I put it back to what @marble jackal had and it's working now. Thanks for your help you two! Maybe I can convince the wife to use you as middle names. 😂
In the Dev section it outputs like this
[
{
"Name": "1st Flr Carbon Monoxide Info",
"Link": "ok"
},
{
"Name": "1st Flr Smoke Alarm Info",
"Link": "ok"
just put petro first
in the name
which seems to be a valid JSON output but the template sensor does not have any states or attr to it
Okay, that is the expected result
Yes but setting it directly is still a possible scenario or like i said the light itself might change its value if it's turned off, and i want to account for it so the helper doesn't get out of sync with the real brightness
yes, but what I'm saying is don't use the helper
make a number template that runs actions
instead of an automation that works off the input_number
You probably used it for the state, you should use it for an attribute.
then you have a separate UI item that doesn't trigger automations and only adjusts your lights
number template?
number template
@worn cloud what is your template sensor config?
hmm, the state mentions: unavailable and the Attr section just says: friendly_name: Ring zWave Sensor Link
template:
- number:
- ...
the template sensor looks like this
@worn cloud posted a code wall, it is moved here --> https://hastebin.com/ocibufivib
use it for what though? run an action depending on the brightness of the light?
no, use that in the UI
to set your lights
your automation runs actions, correct?
based on your input_number
yes
so don't use the input number in the ui, make an template number that has the same actions as your automation
You are now using the template for the state, you should use it for an attribute
post your automations if you don't understand and I'll show you the config
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
It is too long for the state, and the state can't be a list of dicts, an attribute can
I'm off to bed now
ok, thank you for your help - I will read into this
here's my current automations and the script that controls the lights
Ok, so don't expose your input numbers, and just make 3 template numbers
template:
- number:
- name: Light Living Room
state: "{{ expand(area_entities('kitchen')) | selectattr('state', 'eq', 'on') | map(attribute='attributes.brightness') | map('int') | list | average | int }}"
step: 1
min: 0
max: 255
set_value:
- service: light.turn_on
target:
area: kitchen
data:
brightness: "{{ value }}"
ah i see template, as an action
you mean creating an entity from templating? only sensors and binary_sensors
there's templates (Jinja) and then there's template entities which is just an integration based around templates (jinja)
the template: bit was confusing me as i rarely see it since my other entities are !include(d) in, so yeah i just add them like i do with binary_sensors and sensors pretty much
will look into that, thanks
Thank you amd everyine Else.. I was really to deep inside the rabbitcave..
@marble jackal I ended up doing this
- platform: template
sensors:
ringsensorszwave:
friendly_name: "Ring zWave Sensor Link"
value_template: >-
{{ states('group.ringallsensorsinfo') }}
attribute_templates:
data: >-
{% set ns = namespace(zwave=[]) %}
{% set zwave_link = expand('group.ringallsensorsinfo') %}
i cut the code a bit to just show the steps i took and the attr in HA now shows:
friendly_name: Ring zWave Sensor Link
data:
- Name: 1st Flr Carbon Monoxide Info
Link: ok - Name: 1st Flr Smoke Alarm Info
Link: ok - Name: 2nd Flr Carbon Monoxide Info
Link: ok - Name: 2nd Flr Hall Motion Info
Link: ok
but i am not sure how i can extract this data now to show me if any of the Link values go from ok to bad to display me what name has gone bad and if more than 1 goes bad, to display multiples
@worn cloud You need to change the state to a count of those which are bad. Then you can use that as a trigger.
In the condition you can check if the value went up (meaning an additional item went bad) and you can compare the to_state with the from_state to see which one caused the increase
Hey. I was wondering if anyone could help me. Ive got 9 (possibly more in the future) and i want to build an automation which will ensure that only one of them is going to be on. Triggered by any of the switches going on and switching off all other switches from the list except of the one which went on
I believe that the ideal approach to that would be some kind of cunning template populating turn_off service with all the switches except the one which triggered an automation
but ive got no idea how to do that
is anyone able to help with that?
9 what?
9 zigbee switches
and just to add - having more than one switched on at the time will not cause any electrical or hardware malfunction in my case, its not like controlling a fan with multiple windings
i just need an automation which is run by switching one of the devices on and which turns off the other devices
How about putting the switches into a group? Then execute this sequence of actions in your automation:
- turn off the switch group
- turn on switch x
Then in an automation, have 9 triggers, one for each switch, and tag the trigger id as the entity id of the switch. The trigger id can then be used to dynamically set the value of x in the action sequence.
I would create a template sensor with as state the number of switches on, and as attribute a list of switches which are on
Trigger on the numeric state of that sensor being since above 1, then compare the to_state of the attribute with the from_state, to see which one was turned on
Turn the others which are on off
But the approach of Daniel will also work
Or, you could simply create a state trigger with all 9 switches, and use the trigger.entity_id
trigger_variables:
switches:
- switch.switch_1
- ...
- switch.switch_9
trigger:
- platform: state
entity_id: "{{ switches }}"
to: "on"
action:
- service: switch.turn_off
target:
entity_id: "{{ switches | reject(trigger.entity_id) }}"
Not completely sure if a template is allowed for the state trigger though, otherwise also list them there
@fluid glen posted a code wall, it is moved here --> https://hastebin.com/mikosuqoza
wow, it looks like all i was hoping for and even more!
except it doesnt really work 😦 I have tried adding it via YAML editor and get:
Message malformed: Entity {{ switches }} is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
error when trying to save
Okay, so you need to list all the 9 switches as well there
I already mentioned I was not sure this would be accepted
variables:
switches:
- switch.switch_1
- switch.switch_9
trigger:
- platform: state
entity_id:
- switch.switch_1
- switch.switch_9
to: "on"
action:
- service: switch.turn_off
target:
entity_id: "{{ switches | reject('eq', trigger.entity_id) | list }}"```
ok now its saved but doesnt turn off anything:
Error: Template rendered invalid entity IDs: <generator object select_or_reject at 0x7f671ea27d10>
Sorry, corrected above
ok, added this, but now im getting:
Error rendering service target template: TemplateRuntimeError: No test named 'switch.private_office_console_strip_1_l2'.
You also don't need trigger variables now, just variables is okay
My bad, need coffee I guess
Corrected again
you should use anchors on that so you only have to maintain 1 list
I was not sure how that worked in the GUI
variables:
switches: &switches
- switch.switch_1
- switch.switch_9
trigger:
- platform: state
entity_id: *switches
to: "on"
action:
- service: switch.turn_off
target:
entity_id: "{{ switches | reject('eq', trigger.entity_id) | list }}"
not sure if it does work, but just create a separate automation file for yaml ones
works! thank you so much, im literally speechless how quickly youve been figuring out what is the problem and fixing it
Well, I'm feeling bad because I made all those mistakes in the first place 😛
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?
@rancid pelican posted a code wall, it is moved here --> https://hastebin.com/uyekorewac
the automation dont continue after the wait
well the syntax is wrong
and your template is comparing strings
there is no wait action
there's wait_tempalte and wait_for_trigger
which one should i use?
what do you think?
it's supposed to be wait_template
and you have
- wait:
template
so in the comparation values i need to use wait for trigger ?
no
I can't make it any more clear
you just need to use the correct syntax
instead of
- wait:
template
make it 1 line with an _
- wait_template:
i tried that to but not work
because the tempalte is wrong
you're not comparing numbers, you're comparing strings
and you're accessing the state machine when you should be getting the states from the states method
e.g.
You have states.sensor.xxx.state
it should be states('sensor.xxx') | float if you want a number
ok thanks
where sensor.xxx is your entity_id
how can i template the average forecast temperature for say 3 days? I need the dates parsed somehow.
{% set forcast = state_attr('calendar.xyz', 'forecast') %}
{% set end = (today_at() + timedelta(days=3)).isoformat() %}
{{ forcast | selectattr('datetime', '<=', end) | map(attribute='temperature') | list | average }}
@acoustic arch ^^^
Just a quick question, how to include icons to the code? ?EX: icon: mdi:AppleFinder
battery_current:
friendly_name: "Battery current"
value_template: "{{ (states.sensor.*****_battery_power.attributes['current'] | float(default = 0)*1000000)| round(2)}}"
unit_of_measurement: "mA"
icon: mdi:BatteryArrowDown```
{{ state_attr('weather.whatever', 'forecast')[0:2] | map(attribute='temperature') | list | average }} was what I was preparing
I expect it to output an icon that i can see in the HA gui
as soon as he enables hourly, that won't work, that's why i went with selectattr, cause it will work regardless of what's in the forcast
use icon_template: for the field and output the full icon string, i.e. mdi:xyz
This indeed only works for a daily weather entity. However, I think I have 8 weather integration, and none of the hourly versions cover 3 days
yah, i'm not sure as I don't use one
Thanks!
Hi people, I am trying to work with the nordpool sensor to figure out if the price for the current and next hour is below average. And one of the attributes are defined as this:
today: 6.676, 6.573, 6.773, 6.257, 6.784, 6.994, 7.867, 8.205, 8.583, 8.124, 7.928, 7.904, 6.974, 6.66, 6.255, 6.541, 7.027, 7.945, 8.154, 8.49, 8.222, 7.959, 7.043, 6.626
What would be the best way to read eg. value number 4 (6.257)?
I ended up using
{{ state_attr("sensor.nordpool_kwh_krsand", "today")[hour_now]}}
and that at least gives me exactly what I want 🙂
hour_now is defined as now().hour just before
https://dpaste.org/EUM6G
When using this automation action, I get a "message malformed: template value should be a string for dictionary value" error. I'm not quite sure tho, where the error is hiding 😦
Edit: Forgot that Code shall be uploaded to dpaste etc.! fixed that
oooooh...
fixed that. Automation still doesn't work tho. I think, I should that to #automations-archived though
In general, notify.notify isn't a very useful service as it's hard to predict what it will do. Better to create a notify group instead
but it depends entirely on what "doesn't work" means
but if you can paste the template in
-> Templates and it gives the expected output, then I suggest #automations-archived and to follow the standard test procedures
Hello all! I am working to learn about templates using the template editor and I have gotten a couple to report correctly but I am having trouble with a specific one for an "if state_attr" request. I am trying to get a "connected" response when my BT headphones are connected to my phone and no matter how I word it, it always states "disconnected".
{% if state_attr('sensor.pixel_6_pro_bluetooth_connection','connected_paired_devices') == '82:4B:10:25:78:24 (TOZO-T10)' %} connected {% else %} disconnected {% endif %}
Sorry, not sure how to paste it in here correctly but would anyone what I am doing wrong?
This is an example of one that reports correctly for me.
{{ state_attr('sensor.pixel_6_pro_bluetooth_connection','connected_paired_devices') }} which returns ['82:4B:10:25:78:24 (TOZO-T10)']
Try {% if '82:4B...' in state_attr('sensor.pixel...') %}
This is because your state_attr output is a list []. In your {% if state_attr..., the statement on the left of the = returns the list, while the statement on the right is a string. Thus the condition of the if is not met.
Thank you so much! That worked perfectly.🙏
@worn cloud posted a code wall, it is moved here --> https://hastebin.com/owomebizup
@marble jackal I tired this
value_template: >-
{% set ns = namespace(count=0) %}
{% set zwave_link = expand('group.ringallsensorsinfo') %}
{%- for item in zwave_link -%}
{%- if states[item.split('.')[0]][item.split('.')[1]].state == "bad" -%}
{% set ns.count = ns.count + 1 %}
{%- endif -%}
{%- endfor -%}
{{ ns.count }}
and then the attribute_templates: that i had showed you before but now i get no results
this is a hard one!
Your ' in the dict keys may need to be "
That's indeed more consistent
Corrected (and again to fix some more quote inconsistency)
It's proper JSON, but I dint know if it needs to be there
Thats amazing; thank you - I just had to change attributes_template: to attribute_templates: and now when the link goes from ok to bad, i can see the sensor state change from 0 to 1 and if 2 are bad, i see the state go to 2. Now based on the state change I can use that as a trigger and then I assume, i can see which sensor has gone bad and display the friendly_name?
Yes, you can trigger on a state change.
In the conditions check if the value increased, and then compare the from_state with the to_state to see which one changed to bad
thank you once again for all your help!!
so added a script for each moon sensor phase to push a ir button so many times depending on sensor.moon state (on script for each phase, can I turn this into one script)? https://hastebin.com/ocurusudaj.yaml one for last quater and https://hastebin.com/elobufajum.yaml for waxing gibbous and the rest assinged the same way, is there a simpler way to consildate all these into one script so a button press calls that script for conditons, would it be if then and repeat in automation?
lol its actually working ok this way so dont need the help thanks to the if-then and else in automation go light working in combo with moon.
alias: moon light
variables:
moons:
moon-first-quarter: 10
moon-waxing-gibbous: 11
target_moon: "{{ moons.get(moon, 0) }}"
sequence:
- condition: template
value_template: "{{ target_moon != 0 }}"
- service: remote.send_command
data:
device: moon
command:
- moon press
num_repeats: "{{ target_moon }}"
delay_secs: 0.4
target:
entity_id: remote.rm4_pro_remote
mode: single
then to call it...
- service: script.moon_light
data:
moon: moon-first-quarter
i have all the moons as their own script and automation looks like this now
it tunrs on the wall light to red on day the moon is a new moon so son knows that day there is no moon, the wall light back to normal color when there is a moon.
Hopefully this is a simple one, I've got 4 templates that I've created that read the energy state of a smart device and do some basic math to give the 'correct' reading, but they dont show up as consumables on the Energy dashboard? not sure what (or if I can) do to amek them show up as such
unit_of_measurement: "Kwh"
state: "{{ states('sensor.chestfreezerusage')|float / 10 }}"
state_class: total_increasing```
Hm, so made those changes but they dont show up as a option still..
unit_of_measurement: "kWh"
state: "{{ states('sensor.chestfreezerusage')|float / 10 }}"
device_class: energy
state_class: total_increasing```
Does the sensor itself work?
when creating a template entity such as a binary_sensor is there a way to refer to itself other than just hard coding the entity name? for example is_state(this.entity_id, 'on')
If you use the new format, there is the this object you can use
this.state == 'on'`
is_state(this.entity_id, 'on') would work for the current state
Well current state is the previous state
so is_state(this.entity_id, 'on') is not equivilent to is_state('binary_sensor.occupied_living_room', 'on') as 'this' referes to the entity object in it's previous state?
All will return the same state
so does that many mean all the is_state on the icons have never worked properly?
Which is the previous state, ie whsts in the state machine. What thefes is referring to as “the current state”
No that will be current because attributes are resolved after the main state
It’s voodoo
Alright, thanks
Also just to confirm which is best practice the this.state == 'on' syntax as TheFes alluded to? over is_state(this.entity_id, 'on') ?
Both are similar
That kinda makes trigger based template sensors different right? Because the this object is created at the moment of the trigger, so it will be the previous state for the attributes as well
Hmm yes
Is_state v == have a minor difference that you shouldn’t have to worry about. But I’d just use this.state == because you already have the state
So for trigger based template sensors this.state and states(this.entity_id) can be different
is the difference when they are resolved? aka if it's in a function like the latter in the previous example by TheFes it's triggered at the end, where as raw this is processed immediatly?
since it resolves on the id
This only applies to trigger based template sensors, as the this object is created at the moment of the trigger, so also in attributes or for the icon, it will be the previous state
For state based template sensors, the state template will be resolved first, and the this object will have the updated state for the attributes and icon template
Alright, thanks
Yeah, shows up if I add it to lovelace.. works fine
Check
> statistics to check if there is an issue with the sensor. Could be caused by the change in unit of measurement
Says "No issue" for the template entities
hi what am i doing wrong here in templating?
{% set battery = '{{states('sensor.oneplus_6t_battery_level')}}' %} {% if (battery >= 50 and battery <= 100) %} full charge {% elif (battery >= 20 and battery <=49) %} half charge {% elif (battery < 20) %} about to die {% endif %}
also i tried
{% set state = states('sensor.oneplus_6t_battery_level') %}
getting this error
TypeError: '>=' not supported between instances of 'str' and 'int'
how to change a sting or a int to a number?
You are nesting templates, remove '{{ and }}' in the first line
And states are strings, so you need to convert that to a number
{% set battery = states('sensor.oneplus_6t_battery_level') | float %}
Are you using this in a template sensor? Either add a default for the float filter, or add an availability template then
is that for in an automation or script? if so you can move the set battery bit to a variables: section
Btw you can also do this 50 <= battery <= 60 instead of using and
thanks it helped❤️
no just for templating details on front end.. but im interested to learn on how could i use this for automation or script
an example of using that exact code in an automation could be used to pass the charge string into a script for example
that type of syntax can be used more or less anywhere to pass in specific data depending on various conditions, one i use is check the value of an input_select then pass specific RGB values into a light.turn_on command
and in scripts and automations you dont need to use the set var = syntax you can just specify variables: at the root level of the yaml and then add for example battery: {{ states('sensor.oneplus_6t_battery_level') | float(0) }}
would be nice if we could use that in configuration.yaml
is there a way to get the model name of a device from the an entity id? i have a special light scenario for the lights in my kitchen based on area due to the types of bulb they are but would rather have that scenario trigger based on the device name just incase i add any other bulbs of the same type to another room (which i believe i have some extra of laying around) couldnt find a mention of it on the templating document page
Roger that, thanks.
I was getting help from TheFes today to get a template sensor that will increament the state from 0 to 1 and so on when the attr Link: changes from ok to bad. But i am having some issues trying to display the friendly_name in attr once that happens
my attr section looks like this:
connection_data:
- Name: 1st Flr Carbon Monoxide Info
Link: ok
- Name: 1st Flr Smoke Alarm Info
Link: ok
- Name: 2nd Flr Carbon Monoxide Info
Link: ok
- Name: 2nd Flr Hall Motion Info
Link: ok
so lets say if the link for 1st Flr Carbon Monoxide Info goes from ok to bad, the sensor state will change from 0 to 1 but i dont know how i can extract just the friendly name from the sensot that just went bad
Okay, as said you need to trigger on a state change.
Then use this condition to check if there was an increase
- condition: template
value_template: "{{ trigger.to_state.state | int(0) > trigger.from_state.state | int(0) }}"
would you know how i can use this in Node?
or would i put this in the same template sensor we made?
Ik don't use Node Red
Use this in a template to get the one which went bad
{{ trigger.to_state.attributes.connection_state | reject('in', trigger.from_state.attributes.connection_state) | map(attribute='Name') | join(', ') }}
Thanks once again, I will try this. Also what if 1 of the sensors is bad and the state goes from 0 to 1 then a 2nd sensor goes bad and count goes from 1 to 2. Will this display the first again along with the 2nd?
Nope, only the 2nd one
If you would like to have them all displayed, you don't need the attribute at all
{{ expand("group.ringallsensorsinfo") | selectattr("attributes.linkQuality", "eq", "bad") | map(attribute="name") | join(", ") }}
That will give you the names of all the bad ones in a comma separated string
im kinda new to HA and yaml, can someone help debug? getting error ( Entity is neither a valid entity ID nor a valid UUID for dictionary value @ data['condition'][2]['conditions'][0]['entity_id'] ) on this condition template https://paste.debian.net/1252484/
i know i can put them each in a condition:template - value_template: format but i had to repeat this {% set hours = 5 %} for each condition and its bugging me. is there a way to simplify? or should i not bother to and just live with it as long as the automation works?
i tried this on the dev tools template but got this error (TypeError: slice indices must be integers or None or have an index method)
How did you exactly try this on
> templates, because this will not work there
This only works in the automation
For
> templates you need to do {% set hours = 5 %} to simulate the variable
so i tried in the automation using the condition type template. but got an error https://imgur.com/a/c3vvz2s
it does save the automation without errors tho just unable to test within the automation with the error.
i tried to trigger it but the actions didnt fire so i guess the conditions are not working https://paste.debian.net/1252489/
You could also put it in one condition like this:
{% set h = 5 %}
{% set c = [ 'rainy', 'pouring', 'lightning', 'lightning-rainy' ] %}
{% set w = state_attr('weather.forecast_home_hourly','forecast')[:h] | map(attribute='condition') | list + state_attr('weather.forecast_office_hourly','forecast')[:h] | map(attribute='condition') | list %}
{{ w | select('in', c) | list | count > 0 }}
variables is not part of the conditions
wow this is the kind of code i was hoping to achieve. this i can confirm working in the templates. i know the UI is kinda wonky when using the test button, but it saves without any error 😄
Thank you so much! this kept me up late for 2 nights, i can now sleep in peace lol
Sleep well then!
Hi,
Please help me with a template for temperature sensors. It was working before, but then stopped working after some update. Basically I need to select lowest value from 2 values.
value_template: "{% set values = [\n
\x20 states('sensor.filtered_outdoor_temperature_1'),\n
\x20 states('sensor.filtered_outdoor_temperature_2')\n
\x20 ] | select('is_number') | map('float') | round(1)| list\n
%} {{ values | min | round(1) if values | count > 0 else 'none available' }}\n
\x20"
What's with all these \n\ rubbish?
value_template: >
{% set values = [ states('sensor.filtered_outdoor_temperature_1'), states('sensor.filtered_outdoor_temperature_2') ] | select('is_number') | map('float') | list %}
{{ values | min | round(1) if values else 'none available' }}
I had pretty bad formatting, didn't understant YAML standards at that time, so used some online resourse to correct it. Unfortunatelly it spoiled the templates. Added thoew /n/ etc
Thanks a lot for the help 🙂
The real issue was that you were applying the round filter too soon
value_template: >
{% set values = [ states('sensor.filtered_outdoor_temperature_1'), states('sensor.filtered_outdoor_temperature_2') ] | select('is_number') | map('round', 1) | list %}
{{ values | min if values else 'none available' }}
Small improvement, mapping to round directly instead of float
In an automation with a template trigger containing multiple entities is it possible to extract the particular entity whose change caused the trigger to fire?
trigger.entity_id should work according to the docs
But these docs seem to be the same as for state trigger
I haven’t actually tried this, I just assumed it wouldn’t work. But maybe I’m wrong. I’ll try
It works, just tested it
The for_state and to_state are also available, just as the docs say
Hi, I'm trying to implement a custom power sensor from current and voltage multiplication. How is this done, when I created the Voltage and Current previously and the sensor entities are: sensor.battery_current and sensor.battery_voltage. My interpretation was like this yaml battery_watts: friendly_name: "Battery power in mWatts" value_template: "{{(state.sensor.battery_current*state.sensor.battery_voltage)}}" unit_of_measurement: "mW" PS: the current is in mA, and the voltage is in V
two things are wrong with that
state.sensor.battery_current is a state object, and not the actual state. The state would be state.sensor.battery_current.state, or more correctly states('sensor.battery_current').
second, states are strings and you need to turn them into numbers if you want to perform math operations on them
so...
value_template: "{{ states('sensor.battery_current')|float * states('sensor.battery_voltage')|float }}"
Thanks, also should i add this? value_template: "{{ states('sensor.battery_current')|float(default = 0) * states('sensor.battery_voltage')|float (default = 0)}}"
Yes, you should provide a default if it's possible that they won't have a numeric value. You can do that simply with float(0)
Thank you for your expertise!
Or add an availability_template to check if the sensors provide a correct state
Can anyone help me with implementing this #beta message ?
Currently I'm sending a MQTT message to HA with a running total of water usage at the time the signal is sent. I just want to see the number of gallons used since the previous message.
- platform: mqtt
name: "Water Meter"
state_topic: "metermon/water"
value_template: '{{ value_json.Consumption }}'
unit_of_measurement: 'gal'```
Create a trigger based template sensor which triggers on state changes of this sensor.
Subtract trigger.from_state.state | float from trigger.to_state.state | float to get the delta
ok thanks, im new to this template stuff but i'll give it a try
Hello! I am trying to create a template sensor and it's not working as expected. I want to count the number of open windows in my house. I have a sensor for each window that can be in state "Normal" or "Violated". I also have door sensors that can have the same values, so I want to filter those out on the sensor attribute "definition". A window has the definition "burglar_perimeter_instant" so I created this sensor:
sensors:
open_windows:
friendly_name: "Open Window Count"
value_template: '{{ states.sensor| selectattr("definition","equalto","burglar_perimeter_instant")|selectattr("state","equalto","Violated")|list|length }}'```
But the count is always zero no matter if I open a window. Any idea what I'm doing wrong?
you need to use attributes.definition
like this?:
sensors:
open_windows:
friendly_name: "Open Window Count"
value_template: '{{ states.sensor| selectattr("attributes.definition","equalto","burglar_perimeter_instant")|selectattr("state","equalto","Violated")|list|length }}'```
Like that
No, you need to check if the attribute exists first
selectattr("attributes.definition","defined")
I restarted before you added that check - sensor seems to be working as expected without it. I'll add the check, but what is the down side of not adding it?
ah - right, thanks!
The template will fail if you try to filter on an attribute which is not defined, so you need to first select only those sensors which have it defined
Hi! For a custom sensor I need the day/night state. This is working by using {{ 0 if is_state('sun.sun','below_horizon') else 1 }}. Now I wanted to add an offset. Can anyone guide me how to do it? Is it even possible? Thanks!
use the elevation attribute instead
Thanks!
Hey folks. Been researching this and cant seem to find what I am looking for. I want to add a custom entity that is binary sensor class of running. My automations will togggle this but I need that control. It needs to defautl at startup to 0. I am confused on dealting with trying to set this up. Where and how is baffeling to me. If someone could help out is dunbing this down it would be appreciated.
you don't control sensors
you can use an input_boolean (toggle), or a template switch, but I don't know what you mean by "It needs to default at startup to 0". Do you mean "off"?
I tried this in a template i made one sensor go bad but it does not output anything
Anybody knows what's wrong with this code? Keep getting the "can not read a block mapping entry; a multiline key may not be an implicit key" error
It's to be used in an automation with the sensor as it's trigger
shell_command:
pvoutputcurl: ‘curl -d “d={{now().strftime(”%Y%m%d")}}" -d “t={{now().strftime(”%H:%M")}}" -d “v2={{states.sensor.pv_power.state|round(0)}}” -d “v5={{states.sensor.inverter_temperature.state|round(0)}}” -d “v6={{states.sensor.pv_voltage.state|round(0)}}” -H “X-Pvoutput-Apikey: typeinyourapikeyhere” -H “X-Pvoutput-SystemId: typeinyoursystemidhere” https://pvoutput.org/service/r2/addstatus.jsp
Ah crap, didn;t paste good
Yes i have the sensor as a trigger and when it goes to 1 as an example - the template is coming out blank
.share the complete automation on dpaste.org
shell_command:
pvoutputcurl: ‘curl -d “d={{now().strftime(”%Y%m%d")}}" -d “t={{now().strftime(”%H:%M")}}" -d
“v2={{states.sensor.pv_power.state|round(0)}}” -d
“v5={{states.sensor.inverter_temperature.state|round(0)}}” -d
“v6={{states.sensor.pv_voltage.state|round(0)}}” -H “X-Pvoutput-Apikey: typeinyourapikeyhere” -H “X-Pvoutput-SystemId: typeinyoursystemidhere” https://pvoutput.org/service/r2/addstatus.jsp
i am replicating it in Node as i have moved all my automations over - just dont know how it would look in yaml now. And i know you dont use Node, which is not in my favor
I have a trigger which is template you helped me with and when it moves from 0 to 1, i see it fire into a template which i pasted from above but the string is coming out empty
And this one works good for me but if a 2nd sensors goes on while the 1st is on, they both show up even though i have already been notified from the first already
Yes, I asked you which of those you wanted, but you didn't reply
But those trigger templates comparing the for state with the to state won't work in node red
And I don't know how to do that in Node Red
Thanks, yes that is what I intended to say. Working another angle to use a Helper. It looka like a pulldown helper does exactly what I need. Was trying to remove a hangnail with a machete.
So you might want to ask that in #node-red-archived
with the other template you provided; is there a way to use that but to only 1 sensor and then if a new sensor goes bad - to just output that only? Or not possible with this method?
No, that is not possible with your current sensor
You could create a trigger based template sensor out of this sensor instead of the automation
is there a good way to debug if you have a binary sensor causing all your custom entities not loading other than commenting them out one by one till they work?
hi can someone help me on how to create a sensor based on:
{{ state_attr('light.bedroom_lamp','brightness:')}}
brightness value ranges from 0-255
i want to convert these to 0-0.9 values
dont know where to start
I've been doing lots of work on my template sensors the last few days. I have one that reports a cost value, but it has 4 decimal places (1.9454). How can I round it to be "1.95" with only 2 decimal places?
| round(2)
you would start with this: https://www.home-assistant.io/integrations/template/
state_attr('light.bedroom_lamp','brightness')|float / 255
it MIGHT be the otherway around 255 / brightness, it's been a while since i've done that conversion
it works..thanks
i did the same but missed | before float
one quick question if i want the values 0-255 converted to 0.1-1 then what am i supposed to do?
do you want it rounded to the nearest decimal and the lowest value being 0.1 rather than 0?
min-max / max will always get you in the range of 0-1 if you want 0.1 then you'd need to do something like (brightness + 1) / 256 + 0.05 | round(1)
found a better way as i finally found hwo to do ceil
(brightness + 1) / 256 | round(1, 'ceil')
Tried that, it changes the values a bit but doesn't reduce it to 2 decimal places.
{{ (states('sensor.daily_energy')| float ) * (states('input_number.cost_per_kwh') |float ) | round(2) }}
yeah exactly
((states('sensor.daily_energy')| float ) * (states('input_number.cost_per_kwh') |float )) | round(2)
the first two needed to be in () and then rounded else you were just rounding the last one
((state_attr('light.bedroom_lamp','brightness')|float + 1) / 256.0) | round(1, 'ceil') <-- should do it
Ahh! Makes sense. That works. Thanks!
No problem
isnt working tho
{{(state_attr('light.bedroom_lamp','brightness')|float + 1) / 256.0 | round(1, 'ceil')}}
my brightness now is 3 and its not rounding off to 0.1
That's because my initial post forgot the brackets like I told tango
I edited the post, just add brackets around everything before the round
if you still get 3 then something weird is happening
any luck?
it works thanks:❤️....round(1, 'ceil') what does this part actually do i mean how it works?
it rounds UP to the nearest 1 decimal
floor would round down and just round(1) would do regular round
that's also why you need the +1 on the brightness so it's never 0
okay if i want it to round off to say 0.05 or 0.2 what should i do..just trying to learn
0.05 round(1)
soo ceal for decimal ?
ceil means ceiling as in round up
1 means round to 1 decimal
0.05 would be round(2)
okay soo for floor?
floor rounds down
for 0.2 assuming you wanted that as your starting digit it would be the same but you'd probably have to sanitize the brightness first something like (((((state_attr('light.bedroom_lamp','brightness')|float / 10) | round) + ((255 / 10) | round * 2)) * 10) / 255.0) | round(1, 'ceil')
yeah thanks🤩..will try with some examples....
output min value im getting is 2.1
actually instead of rounding up/off cant we just make a range value to fall into other range?
for example 0-255 to 0.1 -1
rounding up or off what happens is..it isnt just taking the low brightness values at all...is their any alternative way instead of rounding?
thats why you add +1 and use ceil
Is there a way to create a template with multiple attributes?
A template sensor? Sure
Good lord templating is.. confusing x.x
Only if you don't know python and jinja
I dont -.-
Better start learning 😉
I've been trying to setup a template as part of an automation so I can use the same automation for every light-switch in my house (read the name then parse out the location/light it controls) I got it working fine with Deconz, but moving to MQTT and its just totally and utterly broken and I cant make it work at all 😄
It seems like this should work.. but it apparently does 'nothing' ```- alias: "MQTT Light Remote: Long Press On"
initial_state: True
trigger:
- platform: event
event_type: state_changed
# Only look at lights going off to on
event_data:
new_state:
state: "on_hold"
# old_state:
# state: 'off'
condition:
- condition: template
value_template: "{{ trigger.event.data.entity_id.startswith('sensor') }}"
action:
- service: light.turn_on
entity_id: light.office
(I know the action is wrong, thats just a simple 'is the trigger/condition actually working' without overcomplcating things at the moemnt
If Im in events, I can see a 'state changed' for new_state: entity_id: sensor.office_switch_action state: on_hold
Hi could you help me change value 0 - 255 to 0.2 - 1
I seem to fare fine without knowing python 😉
Sounds like I need to abandon this idea for now then, dont really have the free time to setup HA & learn two programming languages 🤷
{{ state_attr('light.bedroom_lamp','brightness:') | float / 255 }}
Not sure how to change these value to 0.2-1
Is it possible to make a sensor in HA that changes the unit_of_measurement based on the assumption that it's better to read 1W rather than 1000mW? And it's better to read 200mW rather than 0.2W. My bad code is here with an if else statement yaml value_template: "{{ {states('sensor.battery_current')|float(0) * states('sensor.battery_voltage')|float (0) if(battery_watts<1000){ return unit_of_measurement: "mW"}else{return unit_of_measurement: "W"}}}
{{ ( 0.003137255 * state_attr('light.bedroom_lamp','brightness') | float(0) + 0.2 )|round(1) }}
Thanks ...it shows like 0.1.... 0.3 like that i want it to show like 0.12 0.15
Two numbers after decimal
Change to |round(2)
Tried but no changes
Exactly like this? {{ ( 0.003137255 * state_attr('light.bedroom_lamp','brightness') | float(0) + 0.2 )|round(2) }}