#templates-archived
1 messages Β· Page 168 of 1
ok so value template is for the on state ?
ok cool
so i just do {{ is_state('binary_sensor.geyserwiseapielement', 'on) }}
What do you expect this switch to do when you toggle it?
@marble jackal thats different. thats the turn_on and turn_off sections of the template switch. im just refffering to the state part of it
i think
I know that, but if the binary sensor represents the state of your switch, turning your switch off should cause the binary sensor to turn off as well
well this is what i have
switch:
- platform: template
switches:
geyserelementswitch1:
value_template: "{{ is_state('binary_sensor.geyserwiseapielement', 'on') }}"
turn_on:
service: rest_command.geyserelementturnoff
data: {}
turn_off:
service: rest_command.geyserelementturnoff
data: {}
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as 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.
sorry
- platform: template
switches:
geyserelementswitch1:
value_template: "{{ is_state('binary_sensor.geyserwiseapielement', 'on') }}"
turn_on:
service: rest_command.geyserelementturnoff
data: {}
turn_off:
service: rest_command.geyserelementturnoff
data: {}
you're turning it off in both?
arg sorry will fix off to on in rest service
If that rest command causes the binary sensor to turn off, that will be fine
the rest commands work if i go into developer tools and services and run those manually.
the binary sensor does update yes
ππΌ
looks like no errors thanks, just the thing is when i turn the switch on, it immediately goes off because the rest takes a min to update and then the binary sensor probably checks it via the api a bit later as well
binary_sensor.geyserwiseapielement is a rest binary sensor
any way to get around that
Can you recycle friendly names?
I have a motion sensor and a smoke
Detector in the lounge area can I both name lounge ? Or is that bad form ?
they're completely unrelated and can be whatever you want
entity_id has to be unique, and HA will do what it can to ensure that if you don't (such as adding _2, etc.)
Okay so I can make a array with smoke sensors and same name for motion sensors set alarms accordingly thanks for the info
If your alexa to say the Area in which they are, you can also asign them properly to areas, and announce the area names instead of the friendly names
It's a bit more complex though, as the area is not an attribute of the entity, so you need a for loop and a namespace to go through all entities to get a list of the areas
{% set group = 'binary_sensor.alarm_motion_sensors_away' %}
{% set ns = namespace(area = []) %}
{% for entity in expand(group) | selectattr('state','eq','on') | map(attribute='entity_id') %}
{% set ns.area = ns.area + [ area_name(entity) ] %}
{% endfor %}
{% set areas = ns.area | unique | list %}
There a are entities on in: {{ areas[:-1] | join(', ') ~ ' and ' ~ areas[-1] if areas | count > 0 else areas | join }}
@calm drift posted a code wall, it is moved here --> https://hastebin.com/obejaxixem
what did I do wrong! my last post has been knobbled ...
Hi, I am new to home assistant programming. Can someone help me with how to use variables in for loops? I want to get the gas station with the lowest price from a group of gas stations:
{%set lowestprice =100 %} {%set cheapest= states.group.tankstellen.attributes.entity_id[0]%} {%for entity_id in states.group.tankstellen.attributes.entity_id %} {%if((states(entity_id)|float)<lowestprice)%} {%set lowestprice = states(entity_id)%} {%set cheapest = entity_id%} {{cheapest}} {{states(cheapest)}} {%endif%} {%endfor%} {{cheapest}} {{states(cheapest)}}
The problem is that the update of cheapest or lowestprice in the for loop doesn't survive the iterations. The final output corresponds to the values that I defined in the first two lines.
@calm drift [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).
Please help.
Trying to get a list of "installed_versions" of all integrations. Can't figure out the template for this.
Tried {{ states.update | selectattr('installed_version') | list }}
and it says the attribute installed_version does not exist. But I can see it in the state object.
What am I doing wrong?
thanks
it's 'attributes.installed_version'
you need to use a namespace to use the data inside your for loop.
And you can simply expand your group, no need to use the attribute entity_id
You also need to put spaces after the {% and before the %}
{% set ns = namespace(lowestprice=0, cheapest='') %}
{% for item in expand('group.tankstellen') | selectattr('state', 'is_number') %}
{% if loop.first or item.state | float < ns.lowestprice %}
{% set ns.lowestprice = item.state | float %}
{% set ns.cheapest = item.entity_id %}
{% endif %}
{% endfor %}
{{ ns.cheapest }} {{ ns.lowestprice }}
Hey, quick question, i have a aqara door sensor, it has two states, either its open or closed, but im pretty sure that in the box where i have to enter the state, if i enter open it wouldn't work, so i wanted to ask if "open" or "on" should be used there ?
check
> states, but the state for a binary sensor is on or off
the gui translates it based on the device class
ok its off now while closed π so that means on would be open π thanks π
That could work if you have a my_alarm integration, but I doubt that this is the case. What are you trying to do here?
@marble jackal sorry that should read assensor:
- platform: template
sensors:
my_alarm:
entity_id: sensor.nnudphone_next_alarm
friendly_name: 'MyAlarm'
value_template: >
{% if state_attr("sensor.nnudphone_next_alarm","Local Time") != None -%}
{% set my_alarm = state_attr("sensor.nnudphone_next_alarm","Local Time").split("GMT") %}
{{ my_alarm[0] }}
{%- endif %}
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
sensor:
- platform: template
sensors:
my_alarm:
entity_id: sensor.nnudphone_next_alarm
friendly_name: 'MyAlarm'
value_template: >
{% if state_attr("sensor.nnudphone_next_alarm","Local Time") != None -%}
{% set my_alarm = state_attr("sensor.nnudphone_next_alarm","Local Time").split("GMT") %}
{{ my_alarm[0] }}
{%- endif %}
and please edit your post the next time
instead of posting a new one
your indentation is completely off
well, my_alarm: and everything under that, should be indented
ok thanks will look at the formating again. I am new here so please forgive the etiquette errors. I've been in IT 45 years, this column dependant stuff reminds me of cobol on punch cards back in the 70's, you would have thought IT could have moved on...
indentation is very important in yaml
sensor:
- platform: template
sensors:
my_alarm:
friendly_name: 'MyAlarm'
value_template: >
{{ state_attr("sensor.pixel_5_next_alarm","Local Time").split("GMT")[0] }}
availability_template: >
{{ not state_attr("sensor.pixel_5_next_alarm","Local Time") is none }}
Thanks @marble jackal do you mind spelling it out for me? I don' t understand where you mean to put that.
Well, as installed_version is an attribute of the update entity, you first have to go a level deeper to access it. So instead of selectattr('installed_version') your would have to use selectattr('attributes.installed_version')
not sure what you are trying to achieve here though, this template will give you the entire state objects of all your update entities
Thank you for your help much appreciated.
Oh, I see I forgot to replace my sensor with yours again, but I guess you figured that our yourself π
thanks! any advice where I can learn more about programming in home assistant.. should I look for a jinja tutorial?
Links in the channel topic
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use https://www.codepile.net/ or https://paste.debian.net/ to share code or logs
Hey all π is it somehow possible to create automation that shows the time left of a dumb dishwasher ?
im kinda getting the idea to get the thing to notify me when its done ( will try that later today ) but it would be perfect if i could make a card that states time left π
Create a timer entity based on how long the cycle takes? No template required
but isn't it like sometimes a bit longer and sometimes a bit faster ?
its connected through smart socket, maybe it would use different w in different steps or so ? π that was kinda my idea of the plan ( forgot to mention it π )
and like if i use different program the time would also be different...
You need to figure all that out before you try to write code for it
thats why im asking here, hopefully someone has something similar done already π or is it again the false # for this ? π
I suggest a forum post
My dishwasher shows the time the program takes when I select it. I don't think dishwashers do some calculations like laundry washing machines usually do, but yours might proof me wrong there
He said it's dumb
i was thinking like it could take a bit longer when the water from line is colder than usual , or the waste water is a bit less because its stuck in some bowls what have been turner around and so on
its dumb in a way it's not home connect or so π
watch the power on the circuit
that's waht I do
however, if your washer has cycles, it's a PITA to determine the end within a reasonable time frame
you basically have to know the number of cycles (mine has 5) in order to get the EXACT end time. Otherwise you can just put a delay off and get your notification 4 minutes late
it should be like 2 different programs at most here π
hence why washers are a PITA
PITA ? π
PAIN IN THE ASS
π
this is mine
so for the job done notification, there is a really small bump, then there is like 10min of nothing and a bit bigger bump and its done, so i could use that for finish notification ?
like in this one https://imgur.com/a3TwDGr 22:51 small bump, 23:09 done
well Yours worse ;D
how were you able to post image here ?...
i have unlimited power
what do you mean with that ?
oh ok, got it π
anyways, make a template binary_sensor that is on or off based on the power level
you might need 2
it depends on how many 'blips' you have when it's not running
anomalies, like when your the power jumps but the washing machine is off
yep
just rechecked with the queen of the household, from what i've understood so far, we are using only two modes of the dishwasher, so that would makes things a bit easier π
yeah, but do those modes have 'sizes' to them?
sizes ?
like, my washer has a bunch of modes, but you set the water level
or the clothing amount
nope, just simple 70c for her and 70c plus all three extra options for me
dishwasher here π
so no clothes, or we have been doing it all the time wrong π
well run each one, see how they differ, then come up with an automation that senses them
or
just make a template sensor that's on/off depending on the power. Then make an automation that notifies you if the sensor is off for x minutes
but keep in mind, that method will not notify you exactly when it's finished.
trying to get the exact finish is going to require you to play around a lot and you'll have to test this with trial and error.
because there's no "1 solution fits all" for this
each of the small bumps are 10w - 11w and then there is a big pause, then comes 47,6w ( and a bunch of other w's ) and after like 3 min its 0w. thats the end sequence thats been almost the same for all cases i have
pause is like 16 - 20 min
can i get it to work without the template ? im using GUI for 99% of the stuff i do here, and have really no knowlage in other stuff for now...
in the pause time its using 3,9 - 5w
so thats all the info im having on the end sequence π
you'd have to make an input boolean and turn it on and off with an automation based on the power.
or use the power as a trigger
the just 70c mode has only 4 fat spikes https://imgur.com/bsXnMz6 and the 70c mode with all three options has additional 2 slim spikes https://imgur.com/rtispC3
You're going to have to get creative with your automations
I'm not sure how else to explain this to you
im starting to think how could i get this to work but its like so messed up π
this is something that you will need to do as none of us have your hardware
so trigger, power over 1500w, then wait for trigger 3,9w - 5w for more than 16min ( and just keep waiting until this happens ), then wait for trigger 0w and send notification
makes sense ? π
seems to be an #automations-archived now, so im moving this mess there π
Short question: I cannot use templates in lovelace cards? I would like to dynamically change the name of a sensor card
no, you cannot
oh and thanks of course @mighty ledge but the estimated time left is a huge headache to make, so im just leaving it for now ...
Depends on the card, mushroom template cards support templates, but most cards don't support them
Hi There,
I have a light switch (no dimmer) and bought a smart bulb with temp and dimm. I am using mushroom light card and I set the entity to the Light bulb so I can have the temp and dimm control and a script on Tap which toggles the switch. The issue is I cannot control the icon color.
Do you pepps have any ideas about this? I'm new to HA.
I'm trying to figure out the last time an attribute of an entity was changed, so I can utilize it as a condition for an automation. Do attributes have the last_changed property accessible somehow? I referenced the awesome post from petro (https://community.home-assistant.io/t/last-updated-state-and-last-changed-in-lovelave/101701) and tried this: {{ as_timestamp(states.climate.grill_climate.attributes.current_temperature.last_changed) | timestamp_local }} (with and without the timestamp wrappers) and didn't get the expected returns (either got nothing, or None)
Do I have to wrap that attribute as it's own template sensor to achieve what I'm trying to do?
last_changed is a property on the state object and applies to the whole object - there isn't a separate timestamp for each part of it
if you want to track a specific attribute, make a template sensor for that attribute and then track the last_changed time for that new entity
Hey, I use this code in a markdown card to track train departures.
And this one is for when the train is on time:
{{ (state_attr('sensor.kode_to_goteborg_c', 'planned_time')| as_datetime | as_local).strftime('%H:%M') }}
But I also want the attribute IF the train happen to be late, it will be attribute "estimated_time" and I just go:
{{ state_attr('sensor.kode_to_goteborg_c', 'estimated_time') }}
Its fine, it will show me "None" if its on time.. but only when its not on time there will be a time here. And then I would like that time to be shown with strftime('%H:%M').
But if I go:
{{ (state_attr('sensor.kode_to_goteborg_c', 'estimated_time')| as_datetime | as_local).strftime('%H:%M') }}
It gives me an error that it has to be a string or number, but since its on time there is no number there. Is there a workaround to not give me this error when the train is on time? π
we can't help you without knowing what estimated_time looks like
Sorry, now when the train is on time it says: estimated_time: null
right, but we need to know the format when it's going to be late.
Ah! Its like the planned time so its like this: 2022-07-15T10:52:00+00:00
{% set etime = state_attr('sensor.kode_to_goteborg_c', 'estimated_time') %}
{% if etime is not none %}
{{ (etime | as_datetime | as_local).strftime('%H:%M') }}
{% else %}
On Time
{% endif %}
Awesome! Thank you very much! Can I use this more complex code in markdown-card aswell? Duck DNS is down so I cant try now π
Yes, you can use this in a markdown card
great, thank you!! You're awesome guys!
@autumn matrix posted a code wall, it is moved here --> https://hastebin.com/vuhavodese
Thank you @silent barn
I'm trying to use "states" in an is_illuminance (IF statement) but it does not seem to work. I get the error: Message malformed: expected float for dictionary value @ data['below']
If I change int to float I get the same error. I dont see a data part else I could have used data_template. Any idea's?
It probably doesn't support a template. Use a numeric_state condition with a value_template instead
or a template condition
hmmm with that I get Message malformed: expected float for dictionary value @ data['action'][0]['choose'][0]['conditions'][0]['below']
- condition: numeric_state
entity_id: binary_sensor.presence_21
below: "{{ states('input_number.luxbesturings_zolder_grenswaarde') | int }}"```
You can not apply a template directly in the below field
that explains why it doesnt work either with the IF statement
easiest would be to use a template condition
btw that condition above doesn't make sense, a binary sensor is on or off. It doesn't have a numeric state
if:
- condition: template
value_template: "{{ states('sensor.zolderlux') | float < states('input_number.luxbesturings_zolder_grenswaarde') | int }}"
then:
you are right.. selected the wrong entity
let me check the value_template because thats new to me
no errors any longer @marble jackal
This seems to work! awesome. Thx!
if:
- "{{ states('sensor.zolderlux') | float < states('input_number.luxbesturings_zolder_grenswaarde') | int }}"
then:
should work too
(example here https://www.home-assistant.io/docs/scripts#wait-variable)
and I don't know if the following will works (it works with conditions:):
if: "{{ states('sensor.zolderlux') | float < states('input_number.luxbesturings_zolder_grenswaarde') | int }}"
then:
The last one will work as well, but @autumn matrix seemed to be using the GUI, that's why I provided the full condition
is there a way to limit a "for" by range in a template? I'm using this template:
{%- for x in state_attr('sensor.sonarr_upcoming_media', 'data') %}
{%- if x.title is defined %}
{{ x.poster }}
{{ x.title }} - {{ x.episode }} ({{ x.number }})
{%- endif %}
{%- endfor %}
And want to limit the results to the first say 5 entries, not the whole gamut. There's another sensor I have that has the value I'd like to use (sensor.sonarr_upcoming).
The easiest way would be to collect them all in a list and just output the first 5
You'd need to use a namespace for that
Wouldn't this work
{%- for x in state_attr('sensor.sonarr_upcoming_media', 'data') %}
{%- if x.title is defined and loop.index <= 5 %}
{{ x.poster }}
{{ x.title }} - {{ x.episode }} ({{ x.number }})
{%- endif %}
{%- endfor %}
Not sure if the index starts at 0 or 1
You could always slice the first 5 off the array to start with π
{%- for x in (state_attr('sensor.sonarr_upcoming_media', 'data') | slice(5)) %}
Now that's some thinkin'
loop works, slice does not. is there a way to make the 5 based on the value from sensor.sonarr_upcoming?
What does that sensor produce?
the state is an integer
Because if it loops, it should be sliceable
I did add brackets around the slicing of the state_attr, and those are important
Am I doing something wrong or does delay: '{{ states("input_number.cameraactivatie_focus") | int }}' not work. Tracing looks like this (see below) and done stays at false
Executed: 15 juli 2022 18:12:09
Result:
delay: 120
done: false
i copied what you had exactly doesn't work. managed to use {% set y = upcoming %} so I think i'm good
thanks for the help, i spent more time than i care to admit bashing my head to get that to work
When i manually trigger the script it works but when the automation triggers the same script delay is stalling
Perhaps the automation triggered again?
yes that was it.. and it was set to restart
so restart will kill everything that is still running?
yeah, perhaps it should be a message in the trace? script interrupted by restart of automation
I think it says that it triggered again
doesn't show up here... perhaps because the automation triggers a script
and i'm doing a trace on the script
You keep saying 'script', and you can call a script that runs in parallel and won't be killed
my automation indeed executes a script
and my automation was set to restart
and on restart the script that was running on the background stays in limbo
yeah i appreciate it. I was suggesting an imrpovement so that you can see when a script is killed π
ill do that π
I didn't know what slice does, bit it seems to cut a list in parts. Don't know how that would work for the for loop though.
{{ range(3) | slice(3) | list }}
[
[
0
],
[
1
],
[
2
]
]
hoping to get some direction/assistance. Getting the following error on my sonos_say script. I looked around online and didn't find any specifics. Where can I share the YAML code so a second pair of eyes can help me?
Sonos TTS script: Error rendering Sonos TTS script delay template: TypeError: '>' not supported between instances of 'NoneType' and 'int'
online YAML checker shows no errors
You are first waiting until the player is not playing
At that point there will not be an attribute media duration
So you will be checking none > 0 which is not allowed
OK. looking again π
Hi all. I previously had a template that looked at the forecast object in weather.dark_sky and summed the precipitation. I am now getting the error "UndefinedError: 'dict object' has no attribute 'precipitation'. Here is the orig. template used. Any ideas?
{{state_attr('weather.dark_sky','forecast') |map(attribute='precipitation')|map('float')|sum | round(2)}}
Is your dark sky sensor still working?
hi guys, i use this switch template on my yaml file, but i would like use it on button card, it is possiible? i dont want use this config anymore on yaml file.
@thick cipher posted a code wall, it is moved here --> https://hastebin.com/lazivavogi
I believe so, if I just pull the state there is info in the forecast and current weather info
@mortal oasis posted a code wall, it is moved here --> https://hastebin.com/avazusudeb
You can try this:
{{ state_attr('weather.dark_sky','forecast') | selectattr('precipitation', 'defined') | map(attribute='precipitation') | map('float') | sum | round(2) }}
This worked! Thank you! Will check out the documentation, not sure I follow what the 'defined' does but it works!
It will select only those items which have precipitation defined, otherwise the map filter will error on the ones missing it
How would something like this be accomplished?
{% set test = 'sensor.weather_temperature_over_50' %}
{{ (now() - states.test.last_updated).minutes > 5 }}
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'
Yeah that didn't work.
{{ (now() - states.test.get('last_updated', now())).minutes > 5 }}
TypeError: 'NoneType' object is not callable
{{ (now() - (states.sensor.test.last_updated | default(now())-timedelta(seconds=1))).seconds > 300 }} works
There is no minutes attribute in a timedelta
It didn't work with seconds either. I'll try this one.
now, because if test doesn't exist, there is no last_updated object
BTW don't you mean sensor.test or at least some domain
that could be your error
oh wait
you need to do this
Seems impossible to access the variable. It's reading sensor.test as you said
{% set test = 'sensor.weather_temperature_over_50' %}
{{ (now() - states[test].last_updated).minutes > 5 }}
That worked. After I switched out to seconds of course. Thank you.
How can I replace today_at(next_start) with now + 3 hours let's say?
{% set weather = 'weather.openweathermap' %} {% set forecast =
state_attr(weather, 'forecast') %} {% set n = today_at(next_start).astimezone(utcnow().tzinfo).isoformat() | string %} {%
set temp = forecast | selectattr('datetime', '<=', n) |
map(attribute='temperature') | list %} {{ temp | select('>', 50) |
select('<=', 55) | list | count > 0 }}
(utcnow() + timedelta(hours=3)).isoformat()
FYI .isoformat() is always a string
so that | string is useless
Thank you!
Hmmm this does not seem to work?
type: no_motion
platform: device
device_id: 94bfcdbd75a0e1e2dbbc5d639f34f0ec
entity_id: binary_sensor.presence_38
domain: binary_sensor
for:
hours: 0
minutes: "{{ states('input_number.bewegingsbesturing_garage_timeout') | int }}"
seconds: 0
id: PIRGarage
I get the error message: Message malformed: expected float for dictionary value @ data['for']['minutes']
let me see if i can find that out
@inner mesa
platform: state
entity_id: binary_sensor.presence_38
to: "off"
for: "00:{{ states('input_number.bewegingsbesturing_garage_timeout') | int }}:00"
id: PIRGarage
Would this be it?
you don't need the |int there, but I would expect that to work
If not, separate the components as you originally and as shown in the docs: https://www.home-assistant.io/docs/automation/trigger#holding-a-state-or-attribute
Hello, I'm trying change the position of my blinds by 10 percent
I looked at this : https://www.home-assistant.io/integrations/cover
I'd like to do something like
data:
tilt_position: position +10
Do I have to create a variable ?
No, you just need a template calculated based on the current state
and how do I do that ?
service: cover.set_cover_position
data:
position:
{{ states('Rollladensteuerung.current_position') -10 }}
gives me '[object Object]': null
Does anyone know how to convert this mqtt message into Homeassitant sensors: 20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;
Rollladensteuerung.current_position is not an entity_id
you have to use an actual entity
and all states are strings, so you need to use |float before using the value in an expression
Ok, my entity_id is cover.rollladensteuerung
then you need to use that
position: "{{ state_attr('cover.rollladensteuerung', 'current_position')|float - 10 }}"
Thank you π
somehow this is not working while it worked with one state function.
could it be that only one state is allowed per automation?
i'm a bit confused π«€ . Can anyone spot the problem? it just doesn't trigger
hello, how can I check last_triggered time for my nuki door lock?
lock.bottom_door_opener_lock
You're not actually doing anything
hi guys what is wrong in this template?
time_remaning:
friendly_name: "Tempo restante"
value_template: >-
{% if is_state('script.contagem_zona_1', 'on') %}
{{ states.timer.zone1.attributes.remaining }}
{% elif is_state('script.contagem_zona_2', 'on') %}
{{ states.timer.zone2.attributes.remaining }}
{% elif is_state('script.contagem_zona_3', 'on') %}
{{ states.timer.zone3.attributes.remaining }}
{% elif is_state('script.contagem_zona_4', 'on') %}
{{ states.timer.zone4.attributes.remaining }}
{% else %}
Em espera
{% endif %}
thanks
What is wrong?
looks like you're printing out some state objects, but maybe that's what you want?
this isn't like a job interview, so explain what isn't doing what you expect rather than expecting everyone to guess
I wanted to join 4 timers that appeared as the scripts turned on. I don't know if this is a silly question or if it will work.
"join"? you're output 4 different things, but in two completely different ways
<well, okay, you just ninja-edited>
there's no "joining" going on there, you'll just output one of them
watering_zone:
friendly_name: "Zona a ser regada"
value_template: >-
{% if is_state('switch.rega1', 'on') %}
Zona 1
{% elif is_state('switch.rega2', 'on') %}
Zona 2
{% elif is_state('switch.rega3', 'on') %}
Zona 3
{% elif is_state('switch.rega4', 'on') %}
Zona 4
{% else %}
Rega desligada
{% endif %}
i want something like this. But let time be shown. and not something predefined
sorry
your first example will do that for exactly one of them based on the order you listed them in, and only if the timer is paused or stopped
that was wrong
But the idea is when the clock is counting down...π
there's nothing in the entity that shows the countdown
Is it possible or am I dreaming big?
you will be better off building your own timer with an automation and time_pattern trigger
timer entities don't work the way you want
Evening! Having trouble with reading JSON output, anyone around who could help ?
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?
Keep getting "Unable to parse output as JSON" returned in the log and no attributes showing up on the sensor. I am using a python script to json.dumps a string for processing. Tested on two sites and it parsed the data fine. I have tried to use plain output and " | jq" output with no luck.
Unable to parse output as JSON: { "Non-Spin_deploy": "0", "Non-Spin_recall": "0", "Watch_Date": "", "Watch_start": "", "Watch_end": "", "ocn_start": "2022-07-18", "ocn_end": "2022-07-24", "ocn_cancel": "0", "ers_deploy": "0", "ers_recall": "0", "prc_deploy": "0", "prc_recall": "0", "rr_deploy": "0", "rr_recall": "0", "updated": "2022-07-16 19:07:36" } { "Non-Spin_deploy": "0", "Non-Spin_recall": "0", "Watch_Date": "", "Watch_end": "", "Watch_start": "", "ers_deploy": "0", "ers_recall": "0", "ocn_cancel": "0", "ocn_end": "2022-07-24", "ocn_start": "2022-07-18", "prc_deploy": "0", "prc_recall": "0", "rr_deploy": "0", "rr_recall": "0", "updated": "2022-07-16 19:07:36" }
How are you parsing it?
- platform: command_line
name: Ercot Notices
command: "python3 /config/enotice.py"
value_template: "{{value_json['value']}}"
It kinda looks like you have a list of dicts without the []
I have specified all the attributes as well.
What was logged doesn't look valid
hmm... i'm a json newbie .... I was mirroring another json file and it didn't have those... do I wrap the whole output in [] after the {} ? IE: {[ ]} ?
Other way
I had a 50/50 chance lol
Perhaps describe the data structure you really want
I switch to JSON to get around the 255 char limit ... Easier to address items individually as attributes than parsing the entire string to get what I want. Hopefully that answered what you were looking for.
No
JSON should be "Field Name":"Field Data" it will be that format the entire string. So that would translate in HA as "attribute_name":"attribute_data"
I tried the [] wrapping and it didn't work either.
did an online json validator (jsonlint.com) and it said it's valid. so i'm very confused.
What you posted in the log is a set of dicts, but not a list
Perhaps share what you're actually sending
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as 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.
Share the script or the output from the script?
The JSON
This is the full output:
{"Non-Spin_deploy":"0","Non-Spin_recall":"0","Watch_Date":"","Watch_start":"","Watch_end":"","ocn_start":"2022-07-18","ocn_end":"2022-07-24","ocn_cancel":"0","ers_deploy":"0","ers_recall":"0","prc_deploy":"0","prc_recall":"0","rr_deploy":"0","rr_recall":"0","updated":"2022-07-16 20:07:00"}
I just noticed that. That is bizarre. I only output one set of data
could HA be sending the command twice ?
No idea
... Might have found something, checking into it. If it's what I think it is, can we pretend this conversation never happened today....
ok. I was never here, this never happened. Thanks for opening my eyes.
So I have a problem with a template switch whose goal is to turn on/off recording of my security cameras
https://www.codepile.net/pile/QDOQ2rl7
Is the automation that works without issue, I tried converting it to a template switch
https://www.codepile.net/pile/lL8preLz
however it fails to load the package its in and I cannot see any error in the logs making debugging difficult
Sheesh. That's a giant template
You should really turn that into a multi line template so that it's actually readable
I am not super good with Yaml, especially multi line. I did break it down better in the second
My ultimate goal is to make this into a blueprint
I don't see the difference
first, you're still using data_template: over 2 years after it was deprecated
second, your indentation is not consistent. I suggest fixing that first
beyond that, I'm not going to try to parse the that giant single-line template
Not gonna lie, I found data_template on some forum post because as much googling as I have done I cannot find a page that actual details how to use this
data_template or how to even problem use templates in this manner seem to be entirely undocumented from what I can see and the examples are lacking
there's lots of documentation in the channel topic here
There is a fair amount on various template functions, but combining them or even finding stuff such as what attributes can be used with selectattr are entirely missing
Not to mention the bug currently on github where how the developer tools don't function the same as yaml currently
So far even getting data_template to work has been brute force from various blueprints that I know are working
https://www.codepile.net/pile/OrqMGWrP
Here its more indented, took me a bit to get working as nearly every attempt causes it fail without any real indication as to why
Had a quick look, as I'm on mobile, but it seems you don't need the for loops and namespaces.
Is your goal to select all switches which belong to frigate?
And have record or detect in their name?
{% set record = expand(integration_entities('frigate')) | selectattr('domain', 'eq', 'switch') | map(attribute='entity_id') | select('search', 'record') | list %}
{% set detect = expand(integration_entities('frigate')) | selectattr('domain', 'eq', 'switch') | map(attribute='entity_id') | select('search', 'detect') | list %}
{{ record + detect }}
Does anyone know how to convert this mqtt message into Homeassitant sensors: 20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;
Which part do you need?
I need trigger_sensors to use as a condition and then I also will need to know which sensor was true. I know which sensor is true, but without duplicating the variable taking it out of a list and inserting 'or' I was wondering if there's a way to check if my variable is true the way it's setup or do I just need to make another variable to use as a condition without using a list and use 'or'?
You can check if the result of this template is empty or not
It should be empty (null) if they are all false though?
I made the variable false and this still shows true
{{ trigger_sensors is defined }}
{{ iif(trigger_sensors) }}
I checked it's false by switching my expand to listing false variables and it listed all 4
You should not check for trigger_sensors as that is a list of sensors
I assumed that whole template is resulting in a variable
Nope, the expand is a second variable in the automation. Ideally the first variable trigger_sensors could be used to pass data to the second variable simultaneously being used as a condition. I just realized the second variable is what I can use to check if it's defined because that would be empty if it's false.
{% set trigger_sensors = ['sensor.weather_temperature_over_50_cool',
'sensor.weather_temperature_under_50_over_45_off',
'sensor.weather_temperature_under_50_off',
'sensor.weather_temperature_under_45_heat'] %}
{% set results = expand (trigger_sensors) | selectattr('state', 'eq', 'True') | map(attribute='entity_id') | list | join(',') %}
{{ result }}
{{ iif(result) }}
{{ result | lenght > 0 }}
select_sensor: >-
{{ expand (trigger_sensors) | selectattr('state', 'eq', 'True') |
map(attribute='entity_id') | list | join(',') }}
{{ select_sensor is defined }} would this work too? It should be null if nothing is true in the trigger_sensors variable
is defined will not work, as is will be defined, even if the value is none or '' or []
This should work then?
{{ iif(select_sensor) }} looks like it does
Perfect thank you! Always teaching something new.
Fes that is what I am trying todo and thanks for making it more streamlined. My more perplexing question is why whenever I put it into a template switch the entire yaml file fails to load
You are using a multi line template, with a single line notation
@still lodge See this post
And maybe also read the pinned post petro refers to
Doesn't appear to have fixed anything.
https://www.codepile.net/pile/y7KlxNZ2
Its odd that its not loading and yet I cannot find anywhere in any log that explains why
I assume you rebooted, or reloaded template entities?
reloaded template entities. Let me try rebooting
rebooting no change, no obvious error in the logs and the switch is missing
Is the code places directly in configuration.yaml?
No, its placed in its own Yaml file that is loaded via
packages: !include_dir_named packages```
Do you have other packages in that folder which are working?
Yes, I also had this in the same file as another and whenever I uncommented this code both would break
I have now moved them to two separate files so that my lights continue to work, lol
I originally had this in configuration.yaml and it took me a bit to figure out why everything was broken
Does the configuration check under developer tools mention anything
oh right....I have a bug for that
Try now, since last update I have to view the link first before anyone else can
What i can see is that your item template is wrong
You need to wrap that in single quotes, but I think you can simply remove the curly brackets
If I remove the curly brackets it complains
changing to icon_template: {{'mdi:camera'}} didn't help
with single quotes and no brackets however it loads.... intertesting
You need to put quotes outside the template if you use the single line notation
Originally I just used double quotes because it would complain that it was formated incorrectly if it was double quotes there
icon_template: '{{ "mdi:camera" }}'
I just did icon_template: 'mdi:camera' however icon_template: "mdi:camera" did not work
Instead of icon_template: {{ "mdi:camera" }}
it would fail configuration check
Should make no difference, but okay
I agree, hence why I didn't try single quotes before
Why is all of this failing without errors though ?
Why am I not supposed to access state like this states.sensor.something.state?
Ah, I see. Thank you!
I need these items:
Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;
Cresta and the ID are the identifier of this simple weatherstation. It gives the temperature, humidity and battery status. Would like to create a HA-sensor from it π
The quotes around the template are required because it is otherwise interpreted are a dictionary
Sure, thats not my question. Why was there nowhere, not logs nor editor nor reloading that explained why it was failing or even that it was failing
I don't know
Any idea how I would get this to turn off automatically when the trigger is enter ?
https://dpaste.org/82yq2
use another trigger, add an id, and use a template in the state
you don't want "auto_off", you want "turn off when this trigger happens"
state: true doesn't make any sense
Yeah I wasn't sure how to use the 2 triggers together.
Not exactly sure how your suggestion would look in yaml
oik
- trigger:
- platform: zone
entity_id: person.daniel
zone: zone.away_zone
event: leave
id: leave
- platform: zone
entity_id: person.daniel
zone: zone.away_zone
event: enter
id: enter
binary_sensor:
- unique_id: Daniel_Outside_Away_Zone
name: "Daniel Outside Away Zone"
state: "{{ trigger.id == 'leave' }}"
I assume state would be true when leave and false when enter essentially. If I made another template sensor with the same id's, they won't interfere right because it's a separate trigger sensor?
right
Do zones or people entities have any meta data related to one another? For example I'd like to do something if I enter zone 1 and I've been away from zone 1 for one hour or more. Our do I have to go the route of keeping track of that myself with custom sensors?
sensor.matte_last_left_home or something similar and then just update it with a zone left automation
The state of the zone is the number of person entities in it. It had an attribute listing the person entities in the zone
And the state of the person entity will be the zone it is in
I would create a template sensor with triggers for entering and leaving, with an auto_off
I have an error on startup with one of my scripts.yaml files.
Invalid config for [script]: expected a dictionary. Got OrderedDict ... ending in (See ?, line ?)
Free YAML LINT tools show it's valid so I'm wondering if there's a simple way to locate the issue?
You probably put script: at the top
@inner mesa I didn't in that specific file, which is referenced in configuration.yaml by script split: !include_dir_merge_named ./scripts
Does this create the redundancy you are thinking?
No. I suggest moving the files out to help identify the one that's broken
Can you clarify what you mean? Like put each individual script that's in the custom file into its own file and see which errors persist?
No, move them out of that directory/file to eliminate them
having a state and quite a few attributes based on the state being true, I figured to do:```
state: >
{{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}}
attributes:
title: >
{% if this.state == 'true' %}
{{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}}
{% else %} No alert
{% endif %}
simply putting the state template in all of those attributes solves the issue, so I am positive thats ok. Should I have a guard on this too? If yes, what would be best?
Is it a trigger based template sensor?
no just a regular template sensor, based on the state change of sensor.weatherbit_weather_alerts
thing is, all my other uses of this variable are based on an attribute, here however it is the state
Okay, just did a simple check, this works:
sensor:
- name: Test 1
unique_id: 28218f4f-e575-452d-9d0b-8bf7dc22f29a
state: "{{ states('sensor.power_consumption') }}"
icon: mdi:test-tube
attributes:
test_1: "{{ this.state }}"
so does: attributes: title: > {% if states('sensor.weatherbit_weather_alerts')|int(default=0) > 0 %} {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}} {% else %} No alert {% endif %} just to proof the correctness of the logic
sensor:
- name: Test 1
unique_id: 28218f4f-e575-452d-9d0b-8bf7dc22f29a
state: "{{ states('sensor.power_consumption') | float > 0 }}"
icon: mdi:test-tube
attributes:
test_1: "{{ 'Hello' if this.state else 'Bye' }}"
This returns Hello, so it looks like this.state is parsed as a boolean already, so you should not test for a string
right, that could be it!
attributes:
title: >
{% if this.state %}
{{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}}
{% else %} No alert
{% endif %}
for trigger based template sensors it seems to be one state behind
the this variable is created on the trigger, so before the state template is rendered, so it has the previous state
I wonder what will happen in this case then. ofc, manually reloading the template now works fine, no state lag because of that.
test_1 is state based, test_2 is trigger based
for the state based sensor the state and attribute are the same, the trigger based attribute is one state behind
trigger:
- platform: state
entity_id: sensor.power_consumption
from: ~
sensor:
- name: Test 2
unique_id: c4713163-8c99-40bf-9b6b-a0d233456830
state: "{{ trigger.to_state.state }}"
icon: mdi:test-tube-empty
attributes:
test_2: "{{ this.state }}"
good te be aware of that. We had that in custom:button-card, until the triggers_update option was introduced. Didnt realize we had that same effect in the backend too
You could use it to your advantage, can be an easy way to log the last 5 states for example π
you mean recursively template the attributes?
a verrrry stupid question probably:
{{ states("OTGW_Outside_Temperature") }} gives me unknown, while in developer tools it gives me the temp.
add 'sensor.'
got it! i have to learn this each time i tinker hahaha
and slugify it π
like this:
trigger:
- platform: state
entity_id: sensor.power_consumption
from: ~
sensor:
- name: Test 2
unique_id: c4713163-8c99-40bf-9b6b-a0d233456830
state: "{{ trigger.to_state.state }}"
icon: mdi:test-tube-empty
attributes:
prev_1: "{{ this.state }}"
prev_2: "{{ this.attributes.prev_1 }}"
prev_3: "{{ this.attributes.prev_2 }}"```
yes, thats what I meant.. its really getting close the CC variable like this... wonder what Frenck feels about this, because now you are saving history in attributes in the state machine
sensor last_motion would be a scenario to think of using this
sensor:
- unique_id: last_motion_sensor_triggered
name: Last motion sensor triggered
icon: mdi:motion-sensor
state: >
{{trigger.to_state.name.split(' sensor Motion')[0]}}
attributes: &attributes
entity_id: >
{{trigger.entity_id}}
last_triggered: >
{{trigger.to_state.last_changed.isoformat()}}
``` and then add some recursive attributes π
why not just a list
- name: Test 2
unique_id: c4713163-8c99-40bf-9b6b-a0d233456830
state: "{{ trigger.to_state.state }}"
icon: mdi:test-tube-empty
attributes:
history: "{{ this.attributes.history | default([]) + [ this.state ] }}"
would forever grow though
- name: Test 2
unique_id: c4713163-8c99-40bf-9b6b-a0d233456830
state: "{{ trigger.to_state.state }}"
icon: mdi:test-tube-empty
attributes:
history: "{{ (this.attributes.history | default([]))[:2] + [ this.state ] }}"
That's better indeed. I didn't give it much thought yet as I only just noticed that the this object is one state behind for the trigger based template sensors
could you make it max 10 history?
it would be almost literally what we did with the CC Variable, and its history attributes - service: variable.set_variable data: variable: last_motion attributes: history_1: "{{states('variable.last_motion')}}" history_2: "{{state_attr('variable.last_motion','history_1')}}" history_3: "{{state_attr('variable.last_motion','history_2')}}" history_4: "{{state_attr('variable.last_motion','history_3')}}" history_5: "{{state_attr('variable.last_motion','history_4')}}" history_6: "{{state_attr('variable.last_motion','history_5')}}" history_7: "{{state_attr('variable.last_motion','history_6')}}" history_8: "{{state_attr('variable.last_motion','history_7')}}" history_9: "{{state_attr('variable.last_motion','history_8')}}" history_10: "{{state_attr('variable.last_motion','history_9')}}"
@floral shuttle this is maxed at 3 4
wait, I missed the [:2], or?
yep, working nicely:```
- unique_id: last_motion_sensor_triggered
name: Last motion sensor triggered
icon: mdi:motion-sensor
state: >
{{trigger.to_state.name.split(' sensor Motion')[0]}}
attributes: &attributes
history: >
{{ (this.attributes.history | default([]))[:8] + [ this.state ] }}
entity_id: >
{{trigger.entity_id}}
last_triggered: >
{{trigger.to_state.last_changed.isoformat()}}
heck, it copied the new history over to my Area template π - unique_id: last_motion_seen_in_area name: Last motion seen in area icon: mdi:sofa state: > {{area_name(trigger.entity_id)}} attributes: *attributes
that's a good way to be lazy, kudos
yeah. I now see that I could just as well put the {{area_name(trigger.entity_id)}} in my first template, since I split that to only show the Area name π Saves yet another template (and db space on historic attributes....)
note to self: these attributes survive a restart... which Erik introduced after having discussed the trigger based templates for buttons. Had forgotten about that and added a default 'Not yet set' but upon restart see the full history on the attribute. nice.
aren't they basically the same sensor then?
if i have an array of [0,0,0,0,2,4,6,0,0,0]
how do i average just 2 4 and 6?
find first non 0, find last non zero. then average all values inbetween those.... syntax?π₯Ί
I already provided how you can find the right part of your array last time
Now instead of a count of the items in that part, you need to do an average
yes you helped me well last time. I rewritten some parts for my own sake of sticking to something i can understand once i come back to it. I got it working so far:
@acoustic arch posted a code wall, it is moved here --> https://hastebin.com/iherifiwan
all i need now is to write the array position to a time (already working in last version), and see if there is a substatial peak rain compared to average
i know how to average a complete array, but not a part of it.
ill keep searching/googling
and just like that. after 30min
{{ regen_waarden_lijst[0:4] | list | average }}
Wait, I now see the attributes list isnβt updated after it has reached the :8β¦ so it only shows the first 9 elements, and not the last π
then choose the last 9
[-9:]
that will take the first 5 items out of your list, from the one above it will tak [0,0,0,0,2] and take the average out of that
you need to use the start and einde variables you already have
{% set regen_waarden_lijst = [0,0,0,0,2,4,6,0,0,0] %}
{% set start = regen_waarden_lijst.index(regen_waarden_lijst | reject('eq', 0) | list | first) %}
{% set einde = regen_waarden_lijst[start:].index(0) + start %}
{{ regen_waarden_lijst[start:einde] | average }}
yes Petro, thats what I did now, and the list is building and keeps doing so. We do see the state lag Fes described above,
the attribute entity_id updates correctly, while the atttribute history is 1 behind
Maybe I miss something bu why don't you just do this :
{% set regen_waarden_lijst = [0,0,0,0,2,4,6,0,0,0] %}
{{ regen_waarden_lijst | sum / regen_waarden_lijst | reject('eq', 0) | list | count }}
?
Thx I figured out it had to be start and einde. It was just an example. Sorry for making you reply
It was your own example π
Is there a way to get historic data from an attribute?
I have the following:
- sensor:
- name: "downstairs_hvac_action"
state: "{{state_attr('climate.downstairs', 'hvac_action')}}"```
But when I try to get history stats I need an entity id
```sensor:
- platform: history_stats
name: HVAC Upstairs Cooling - test
en_id: upstairs_hvac_action
state: "cooling"
type: time
start: "{{ now().replace(hour=0, minute=0, second=0) }}"
end: "{{ now() }}"```
You need to grab the data out of the DB via an SQL sensor
Hello guys, I was sent here from #automations-archived, I would like to use the foreach operator in a script to print out all of the days and the temperatures that are in the forecast.
I'm a total noob with this, so any help would be appreciated.
Print them where?
To TTS
Thats what I currently have
But instead of the tomorrow, I want it to iterate over the different days in the forecast.
Or is that a bit too much xd
It would drive me nuts
I like it :P
So you can either do what you were suggesting and loop through them with a 'repeat' construct and use the loop index for each day (where you currently have [0]), or construct a big message in a template and send it all at once
Yeah I would kinda like the repeat construction, makes it a bit more tidy and flexible imho
I suggest the former, as it is better documented and easier to do in the UI
Well, with you help i made something thats actually working:
https://www.codepile.net/pile/pZ9El8Z0
now to toss it in an automation and finetune it. Not sure yet how and when to retrigger the automation, but the hard part is done i think.
im sure it can be written prettier but they its now i can understand it
no more big IF ELIF lists to make something work π₯³
This is basically a replication of what
Is there a way to use templates in the general lovelace cards?
I'd like the name: of a gauge: card to be change based on the state of the entity.
Thanks.
turns out I got it to work using https://github.com/gadgetchnnel/lovelace-card-templater
Not exactly straight forward though and not sure if there's reason you shouldn't be doing this.
it's fine, it's just a custom card/modifier
another Q, this one is actually working but I feel like the nested brackets is poor code - I'm just trying to improve the way I write templates.
This entity is provided from a different system through a Long-Lived Access Token. Occasionally it becomes unavailable and breaks some charts.
Goal here is to return 0 when the entity is unavailable. Is there a tidier way to acheive the {% if %} part?
name: TWC Charger Load Always W
state_class: measurement
unit_of_measurement: W
device_class: power
state: >
{% if is_number(states('sensor.twcmanager_charger_load_w')) %}
{{states('sensor.twcmanager_charger_load_w')}}
{% else %}
0
{% endif %}```
I would do this:
{% set value = states('sensor.twcmanager_charger_load_w') %}
{{ iif(is_number(value), value, 0) }}
much more concise and easier to understand
actually, it can be even simpler:
{{ states('sensor.twcmanager_charger_load_w')|float(0) }}
What's the logic there if the entity doesn't exist? does using the float(0) filter mean that it will return a zero be default if it returns null?
it will return 0 if the input isn't something that float can convert to a float
you can test it in
-> Templates
{{ none|float(0) }} -> 0
that's awesome, thanks for explaining
Hi everyone, is it possible to track an energy sensors for changes and depending on the state of another sensor, add the difference to a template sensor? I get the energy from my heat pump via an SDM120 meter, which already returns the energy in kWh. Now I want to split this energy into Heating, Hot Water and Standby. So if the mode is set to Heating, all changes to the energy sensor should be added to a new template sensor Energy Heating.
otherwise I would need to track the power sensor with an integration sensor, but this will most probably lead to differences to the "real" energy sensor from the meter
with mushroom template card i would like to change the colour.
"{%-elif is_state('sensor.sonos_roam1_battery' | float < 70) %}
green"
But i am not so good in code. (as you can see ;-) ) What am i doing wrong ?
is that your complete template?
"{{ 'green' if is_state('sensor.sonos_roam1_battery') | float < 70 }}" should work then
You can probably create a trigger based template sensor and trigger on each state change of your energy sensor
Then based on the mode, add the difference between the to_state and de from_state
otherwise, keep the existing state
state: >
{% set change = trigger.to_state.state | float - trigger.from_state.state | float %}
{% set mode = state_attr('sensor.foo', 'mode') %}
{{ this.state | float(0) + change if mode == heating else this.state }}
with:
trigger:
- platform: state
entity_id: sensor.pump_energy
not_to:
- unavailable
- unknown
not_from:
- unavailable
- unknown
Not sure why I'm getting this
Message malformed: required key not provided @ data['action']
not sure either, are you sure it originates from this automation? Based on the message the action part seems to be missing, but it is present in the link you shared. It seems to be more related to #automations-archived anyway.
Hey all got sent here from #automations-archived I wanted to make an automation that sends me a notification when a window or door changes status, for example living room window opened, or storage room door closed. And all that when the group ( both iPhones ) are not home. I already have the group, and I kinda get the totals basic idea of notifications , in this case I would like to get the super important iPhone notification ( sadly no idea how that thing works ) but the biggest problem is for my plan to work I would have to create two automations for each and every window and door I have so that I would receive a correct message of the exact thing that changed status. Iβm 100% itβs doable in easier way in YAML but so far Iβve done some super basic copy paste YAML stuff so writing and automation fully in YAML definitely not an option for me at the moment . Any ideas how could this be done in GUI ? Or maybe someone has this already done ? π
Thank You ! Will try to get it done a bit later today π
condition: not
- conditions:
condition: zone
entity_id: device_tracker
zone: zone.home
having some problems with this line, i used it from another automation and wanted to add it to the code @arctic sorrel gave a minute ago π
You really don't have to keep tagging me all the damn time @thorny snow
Ok i got that im doing something wrong again π what do You mean with that ?
Oh the @ thing ? π
But it's ok, I'll add you to my blocklist 
i got discord like two days after HA so yep, as new to this as to HA π
condition: device
domain: device_tracker
entity_id: device_tracker
type: is_not_home
this one also didn't work, with didn't work i meant i got an error in http://www.yamllint.com
So at least the YAML Lint says its correct now https://dpaste.org/BBcQu, anything that seems to be wrong here ?
Uhm, I don't see any templates here, this is still #automations-archived territory π
As soon as you start using {{ or {% you are using templates
yep, thanks
So now it should be templates related, hopefully, so i have a entity that has a friendly name, and i have an automation that sends me a message if the state of the entity changes including the name of the entity in the message, but what i want is for the entity to keep its friendly name but have a different friendly name in the message im getting so one of the @Gods here told me this -> Then you'll have to build a really big templates that uses the entity ID to give you a hard-coded name of your choice <- this is the original automation with the message code
you can put a variable in your automation
action:
- variables:
mapping:
0x00158d0008649a33_contact: Window Bedroom
- service: notify.mobile_app_iphone_x
data:
title: "Yep it's happening!"
message: "The {{ mapping[trigger.to_state.object_id] }} just {{ 'opened' if trigger.to_state.state == 'on' else 'closed' }}"
so just add a bunch of variables ?
ohh got it
but add all sensors to that variable
like so ? π
had to edit the message text also ( didn't noticed that at first ) but now it works π Huge thanks ! π any knowledge in iOS notifications ?, i know about #ios_and_mac-archived but it's been quiet so far...
got it, spacing π
back to this - unique_id: weatherbit_alert name: Weatherbit Alert state: > {{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}} attributes: title: > {% if this.state %} {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}} {% else %} No alert {% endif %} currently the state is false, and yet it passes the if....
so I do need to check if the state is actually true after all
was an error in the integration showing no alert (which as I typed this was corrected) but it did show the if this.state not to be solid..
states are strings...
a populated string always returns true π
hi. yes, and a few posts up I tried if this.state == 'true' but that didnt help....
you'd have to know the actual state
python, values are True or False
so I'd expect the string to be 'True' or 'False'
{% set this = states('sensor.weatherbit_weather_alerts')|int(default=0) > 0 %}
{{this == true}}```
my man, that's not what's resolved. That's just in jinja and your comparing objects
is that a sensor or a binary_sensor?
or you can just check what the state is in the states page
its a template binary_sensor, with several attributes
if it's a binary_sensor, ask yourself, what are the only possible states for a binary sensor?
wait, the binary_sensor is on/off, but the state template isnt
because...
heck, I believe I see the light...... this.state is the state of the binary_sensor.....and not the state template..
exactly....
π
thx....
Ah, sorry. I assumed you knew that, and actually used a sensor instead of a binary sensor
@mighty ledge I tested with a sensor instead of a binary sensor, and this.state was actually parsed as a boolean value
did you just put that in a variable though to check if it was? Because this is a normal state object and that means that .state should always be a string
I think my test was faulty indeed
no need to fight over it π it was me who was confused to begin with....
No fight :)
Btw, this is a good use case for the new bool filter. You can use this.state | bool as a test
Hi all,
I have been using home assistant now for years, and I really like it π
I am currently helping to set up a home assistant instance for Project Kamp https://www.youtube.com/c/ProjectKamp (off-grid sustainable living community in portugal)
They have a nice 6 panel solar setup with a giant battery, it is all victron powered and I managed to get the data out of the system through MQTT
Main question:
How do I get an mqtt sensor (in Watts) to to show up in the energy dashboard? I tried templating and integrating, but so far no luck
Shall I share my config what I tried here?
You need to convert W to kWh using the Riemann Sum integral (available in the GUI under Helpers)
Okay I made a integral for the solar component, and it shows in kWh, but it does not allow me to select it as an option in the energy dashboard
Hey folks, trying to figure out how to url enocode a string which seems not possible. I tried with a basic object too but the outpet in dev tools is blank which is confusing to me
{% set test = '{"testKey": "testValue"}'|from_json %}
{{ urlencode(test) }}
It needs:
device_class: energy
state_class: total_increasing
Does anyone know how to convert this mqtt message into Homeassitant sensors: 20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;
I need this part:
Does anyone know how to convert this mqtt message into Homeassitant sensors: Cresta = id , TEMP=00cf, HUM=09, BAT=LOW;`
So, if the message contains βCrestaβ, the TEMP, HUM and BAT values must be placed into a sensor Cresta with attributes TEMP, HUM and BAT with corresponding valuesβ¦
Who can make a template for it?
you!
This is a template that takes that data and turns into a dict that an MQTT sensor can process into attributes:
{% set data = "20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;" %}
{% set ns=namespace(fields={}) %}
{% set fields = data.split(';') %}
{% if fields[2] == "Cresta" %}
{% for item in data.split(';') %}
{% if '=' in item %}
{% set keys=item.split('=') %}
{% set ns.fields = dict(ns.fields.items(), **{keys[0]: keys[1]}) %}
{% endif %}
{% endfor %}
{% endif %}
{{ ns.fields|to_json }}
->
{
"ID": "3601",
"TEMP": "00cf",
"HUM": "09",
"BAT": "LOW"
}
you can put some version of that in json_attributes_template and it will populate the attributes from the resulting dict
I'm having trouble understanding the depreciation of "entity_id" I have a lot of template sensors and I determined their entity_id and use that subsequently all over the place. If I remove that line that sets all the entity_id's in my template sensors, what does their id become? how can I make sure they are named the way I like?
sensors:
p1bucket_midline:
friendly_name: 'P1 Bucket MidLine'
entity_id: sensor.p1bucket_midline
value_template: >-
{% set midline = (states('sensor.wl1_p1_ads1115_a1') | float) %}
{% if midline < 100 %}
Dry
{% else %}
Wet
{% endif %}```
In addition, I experimented by removing that line from 1 of my sensors, and it still shows up and has the original name after even a reboot - but why? (and what happens if I write new ones)?
would change to ```
- platform: template
sensors:
p1bucket_midline:
friendly_name: 'P1 Bucket MidLine'
value_template: >-
{% set midline = (states('sensor.wl1_p1_ads1115_a1') | float) %}
{% if midline < 100 %}
Dry
{% else %}
Wet
{% endif %}```
the entity_id: key was only required to tell the template engine what to monitor to decide when the template needs to be reevaluated
it has no effect on the name of the sensor that you're creating, and you only needed it if the entities to monitor were ambiguous from the template itself
if you just want to monitor sensor.wl1_p1_ads1115_a1, then you can just remove the entity_id line completely
k thanks
is there a way to make a template sensor that shows change over time?
actually its probably not possible as what I am trying to do is check the health of recorder/MariaDB
so my mqtt sensor has these attributes, but is there a way to add that to the integral, can seem to add it trough the helper gui
IT IS WORKING π
thank you @marble jackal
1 more question:
I am pulling information of the battery, and the value can be positive (while charging), or negative (while discharging), how do i separate them into 2 sensors?
Was there a change (and when), that I cannot filter directly with e.g. | selectattr('attributes.device_class', 'eq', 'battery') anymore, but have to filter on the availability of the attribute | selectattr('attributes.device_class', 'defined') before? Just went by chance through some old sensors, where I'm pretty sure, that they worked before, but now I get error messages without the check in developer tools.
Does anyone know how to convert this mqtt message into Homeassitant sensors: 20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;
Zou dit graag willen hebben:
Id=waarde; alle items, die wil ik graag in 1 ha-sensor π
What was not working for you in the answer Rob gave above?
Yes, that has been changed in 2022.6 (or 2022.5, I'm not completely sure)
Something like [ 0, states('sensor.battery') | float] | max for the positive values and [ 0, states('sensor.battery') | float] | min for the negative values
Created a sensor with history_stats, is there some way to reload them without a restart?
no, missing attributes always caused that issue.
No, there wasn't a change. It's always been like that.
if there was a change it was to the attribute itself, specifically device_class, or __getitem__ on the attributes state object. But IIRC that's just an ordered dictionary.
we can't adjust how selectattr behaves, it's a built in to jinja
you can override it, but that was not done
Basically what I'm saying is, nothing was changed in templates. Something may have changed that affects templates. Maybe it's just semantics, but you should understand that accessing an attribute that doesn't exist should always start with is defined
Already changed all my templates. But I'm 100% sure, that it worked without feature check filter in the past. For years and without errors neither in execution nor in developer tools. It selected only the ones with the attribute.
you still aren't understanding what I'm saying
I have templates that are from day 1 that exclude attributes because they didn't exist and caused errors. Nothing changed with that. The state object is a special object, something may have changed on that. All of home assistant is built on state objects. Templates just use them. Something may have changed with that object, specifically with device_class as it's a special attribute. However, nothing changed with templates.
hi, how can Δ± grayscale if contact sensor is closed and if Δ± open sensor, its color on mushroom cards ?
icon_color: "{{ 'yellow' if is_state('binary_sensor.your_door_sensor', 'on') }}"
The default is grey
@spring zenith posted a code wall, it is moved here --> https://hastebin.com/ecexocupud
srry... didnt mean to do that
Its a code in a mushtoom sjablooon. For dashboard.
You started with {% elif that should be proceeded be {% if your statement %} and end with {% endif %}.
So if that was your entire template, it was incomplete
the bottom one. for the collor. I use 1 if and 2 elif... this is not correct?
You can not use < in is_state
You need to use states() | float < 70
well, I am back to using the full template in each attribute, because even {% if this.state == 'on' %} resulted in an error just now: 2022-07-20 16:16:32.470 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: list object has no element 0 when rendering '{% if this.state == 'on' %} {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}} {% else %} No alert {% endif %}' and that on all attributes. Replacing immediately solves the issue
That error comes from the state_attr
thing is, if the binary is on, it means the ``` state: >
{{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}}
this works:```
- unique_id: weatherbit_alert
name: Weatherbit Alert
state: >
{{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}}
attributes:
title: >
{% if states('sensor.weatherbit_weather_alerts')|int(default=0) > 0 %}
{{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}}
{% else %} No alert
{% endif %}
and this causes inconsistent errors:```
- unique_id: weatherbit_alert
name: Weatherbit Alert
state: >
{{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}}
attributes:
title: >
{% if this.state == 'on' %}
{{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}}
{% else %} No alert
{% endif %}```
imight it also be the state lagging 1 state change behind I now realize? like we discussed on another template the other day? thats got to be it. Upon changing from on to off on the main binary sensor, the attributes are still in the previous this.state.. which doesnt happen when using the full template
I don't think that is the case, in our previous discussion I was referring to trigger based template sensors. In that case this is created on the trigger firing, when the templates are not rendered yet
True, different scenario. Still this worked fine (== βonβ) until the source sensor changed. Replacing that as shown above fixed it.
Hi,
How can I create a dummy switch which will be negation of tasmota relay?
Tasmota Relay1 - this is a physical one switch.valves_1
and I need R3= negation of switch.valves_1
Im gonna use R3 just as an indicator (just to animate icon opposit to switch_valves_1)
or maybe I could change something here:
type: picture-elements
elements:
- type: state-icon
entity: switch.valves_1
style:
top: 6.4%
left: 35% - type: state-icon
entity: switch.valves_2
style:
top: 45%
left: 35% - type: state-icon
entity: ! (some kind of negation here? )switch.valves_2
style:
top: 21%
left: 47.6%
transform: rotate(90deg)
image: /local/water.png
https://www.toptal.com/developers/hastebin/ematijefif.java
not working.
But already thanks for your help π
states not state
@frail olive [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).
Ill make it <70> . only 2 lines.
But still no success
https://www.codepile.net/pile/yAKa9px3
Please carefully read what I post
states() | float < 70 not states( | float < 70)
Yes. it works... Srry for misreading π
Hello, is there a command for updating core & supervisor. I would like to do updates using the button on the dashboard?
that's not a question for templates. That'll be #integrations-archived or #automations-archived
Ok thx
And I'm pretty sure there is no service for that. You would need to ssh in and use ha core update for core
As he seems to run superviser, he can use the update entity
And the related service call
I thought that was for updating firmware
are you talking about the update.install service?
with update.home_assistant_supervisor_update?
I've set up an automation for core updates, and I can update from that notification
and update.home_assistant_core_update?
It provides a link to the release notes as well, which I always press first of course
Yes, those, although supervisor automatically updates, I use it for core and OS
ok, TIL
that's great. I stand corrected @lime forge
Thx βΊ
I probably should have clarified, I was referring to the update entities, which is why I said automations or integrations (depending on the route they wanted to go)
it was a toss up between integrations, automations, or frontend
all 3 are better fits than templates.
#TheFesHasAllThe Answers
hmm. ```ValueError: Template error: bool got invalid input 'na' when rendering template '{{value if value|bool is boolean else none}}' but no default was specified
figured the |bool was used just to check for this existence but now its needs a default itself?
used in a binary mqtt sensor like:```
binary_sensor:
- unique_id: amp_left_auditorium_state_binary
state_topic: '70:B3:D5:6F:31:F2/powerswitch-zwave/c5745b57/state'
name: Amp left Auditorium state
<<: &binary
payload_on: 'on'
payload_off: 'off'
device_class: power
value_template: >
{{value if value|bool is boolean else none}}```
that behavior is verbosely spelled out here: https://www.home-assistant.io/docs/configuration/templating/#numeric-functions-and-filters
yes, thx Rob, I had missed that.{{value if bool(value,none) is boolean else none}} seems to fix it. At least in the dev template.
I keep forgetting how to display values as numbers instead of discrete colored blocks?
- name: water_cold
state_topic: 'kelder/coldwater'
unit_of_measurement: 'l'
value_template: "{{ value_json.Volume|int(unknown) }}"- platform: derivative
source: sensor.water_cold
name: water_cold_10min
round: 0
unit_time: h
time_window: "00:10:00"
- platform: derivative
first shows nice graph but second one shows blocks. l/h is not recognized unit?
there are no recognized units, doesn't matter what it is
once you add a unit_of_measurement, the old unitless data needs to be flushed out
or you can purge it
Hi all, I was wondering if there is a simple method for adding a mean/median operation to a template sensor with simple algebraic operations, to receive a 1/10 down sample, or something similar?
I am trying to combine different electrical power measures, to get a better estimate of draw on different circuits, but unfortunately such ratios are very sensitive to desynchronized spikes, which are common in power monitoring.
- sensor: - name: Rest power draw state_class: measurement device_class: power unit_of_measurement: W unique_id: rest_power_draw state: "{{ states('sensor.house_power_draw') | int - (states('sensor.dishwasher_socket_power') | int + states('sensor.kettle_socket_power') | int + states('sensor.kitchen_tv_socket_power') | int + states('sensor.master_bedroom_tv_socket_power') | int + states('sensor.office_pc_socket_power') | int + states('sensor.reku_unit_socket_power') | int + states('sensor.server_socket_power') | int + states('sensor.wolf_boiler_socket_power') | int + states('sensor.lg_tv_power') | int + states('sensor.fridge_power') | int + states('sensor.washing_machine_power') | int + states('sensor.garden_pump_power') | int + states('sensor.vyper_3d_printer_power') | int) }}"
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as 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.
[Rule #6](#rules message): Please do not post codewalls (text longer than 15 lines) - use sites 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 take the time now to review all of the rules and references in #rules.
Any ideas??
What am I doing wrong in this really simple template? sensor.fridge_duty_cycle is a history_stats sensor configured to ratio. In the template tester in devtools, the tooltip shows the value just fine, but in the template {{ states('sensor.fridge_duty_cycle') | float }} it returns unknown. What am I doing wrong?
Nevermind, I borked my templates converting them to the new format. For some reason HA said the configuration was OK, I guess I forgot to save them first.
I have two near identical simple templates. One is working fine, the other is throwing an error.
The working one is {{ states.input_number.remote_pulse_time.state | int }} the faulty one is {{ states.input_number.partial_time_set_kitchen_shutters | int }}
The error I get is: Error: ValueError: Template error: int got invalid input '<template TemplateState(<state input_number.partial_time_set_kitchen_shutters=5.0; initial=None, editable=True, min=0.0, max=60.0, step=1.0, mode=box, unit_of_measurement=s, icon=mdi:alpha-p-circle-outline, friendly_name=Partial Time Set, Kitchen Shutters @ 2022-07-21T01:07:32.750320+00:00>)>' when rendering template '{{ states.input_number.partial_time_set_kitchen_shutters | int }}' but no default was specified
you're missing a ".state"
or really, you're not using states(...) as you should
you see that difference, right?
the big warning box explains why you should use the functions instead: https://www.home-assistant.io/docs/configuration/templating/#states
Got ya. Pretty new at templates and automation. Probably a good idea to embed the good habits straight of the bat. Cheers.
When changing
milliseconds: '{{ states.input_number.remote_pulse_time.state }}'```
to
``` - delay:
milliseconds: {{ states('input_number.remote_pulse_time') }}```
it results in the code being changed to
``` - delay:
milliseconds:
'[object Object]': null```
Searching around it feels like I need to use something along the lines of a `data_template:` entry or `value_template:` entry however I've tried a number of different configurations and it always results in the same change to `null`.
You're missing quotes around your template
Thanks again mate.
#templates-archived I see that a lot of people have trouble with nested json . How to use this is documented here: https://www.home-assistant.io/docs/configuration/templating/#processing-incoming-data and thus I concider it as the holy grale. Yet if I try to process this json string {"Time":"2022-07-21T08:32:48","OPENTHERM":{"conn":"FAULT","settings":18,}} as per the manual with value_template: "{{ value_json.Time }}" and value_template: "{{ value_json['OPENTHERM']['settings'] }}" , I get in both cases the state value unknown .
Am I doing something wrong or is there room for improvement in the manual ?
{% set value_json = {"Time":"2022-07-21T08:32:48","OPENTHERM":{"conn":"FAULT","settings":18,}} %}
{{ value_json.Time }}
{{ value_json['OPENTHERM']['settings'] }}
This works fine for me in
>Templates
.share the entire yaml using these templates
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as 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.
I figured it out. My device sents out not correct json. There is a comma in front of the closing } that should not be there.
Thank you for your response anyway.
Hey, can I get some help setting a target based on the device that starts a script running?
I have Sonoff NSPanels connected via MQTT, Iβve configured it to run a script to start a playlist on my Sonos speakers in the same room itβs in. That works fine.
However, I have different panels in different rooms with different speakers. I want the same functionality to work without having to recreate the scripts for each room. I need to replace the target speaker based on the specific nspanel that calls the script.
Eg in the lounge, I want it to play on media_player.lounge_sonos, but in the kitchen I want it to play in media_player.kitchen_sonos
I canβt even work out how to detect which nspanel has called the script, the logbook just say βsupervisorβ.
Thanks in advance!
uh, that's way over coded....
{{ value | bool(none) }}
I thought so as well, but then I thought he might wat the "on" value instead of true
but on will convert to True
the | bool or bool(x) converts to a boolean, aka True or False
{{ x if bool(x, none) is boolean else none }} is literally identical to {{ x | bool(none) }}
on will be converted to a boolean
because that's what bool() does
{{value if value|bool is boolean else none}} this will return "on" if value is "on"
and none if value is "unavailable"
yeah but the templates for binary_sensors accept true as on
okay, true, I only looked at this template
should have looked at how he used it in the post after that π
MQTT is unique in that you can assign what on/off means with payload on/off
so maybe he didn't set those and left them to default
because that makes {{ value | bool(none) }} perfectly fine
which I think is 'on' or 'off'
Ah, yes, he left payload_on and off as 'on' or 'off' instead of True/ False
I don't use MQTT myself, so that's a bit of a blank spot for me π
he can just remove the quotes from on and off and change the template
it's easy, you'd pick it up in 5 minutes
it's all documentation
I helped people for 3 years before actually using it myself
99% of questions for that integration can be solved with the docs
payload_on: 'on'
payload_off: 'off'
There's no Chinese in this indeed
when people say the docs aren't good enough, they just don't understand the docs
Yeah, that's why he needed that verbose statement
so if he changes that to
payload_on: on
payload_off: off
or
payload_on: true
payload_off: false
then {{ value | bool(none) }} would be all he needs
that's the only binary_sensor platform that doesn't default true/false meaning on/off
that uses templates, so keep that in the back of your mind
also, removing the quotes from on/off in yaml change the field to a boolean that resolves to true or false
that's why quotes are needed when checking for on/off states everywhere
because yaml naturally converts them when they don't have quotes
understood!
Is there a built-in function or filter to determine the most frequent element in a list -- sort of like Python Counter's most_common() function?
Output : Dog```
I'm trying to create a template room presence sensor that combines data from three ESPresense mqtt_room sensors (an Apple Watch and two iPhones), and if two of the three sensors report the same state, I would like the template sensor to have that state, or if they all report different states, default to the state reported by the Apple Watch.
no easy way to do taht
{% set items = ['a', 'a', 'd', 'a', 'c' , 'b', 'b', 'a', 'd' ] %}
{% set ns = namespace(most_common={'item':none,'count':none}) %}
{% for item in items | unique %}
{% set cnt = items | select('eq', item) | list | length %}
{% if ns.most_common.item is none %}
{% set ns.most_common = {'item':item,'count':cnt} %}
{% elif cnt > ns.most_common.count %}
{% set ns.most_common = {'item':item,'count':cnt} %}
{% endif %}
{% endfor %}
{{ ns.most_common.item }}
Thank you! I had been trying to convert some Python code to iterate through the list and count the number of occurrences of each element, but I was having trouble getting it working. I was hoping there might be an easier way, but this should do the trick. Appreciate your help!
Hey guys i need some help to understand how to name files (images) by the source.
2022-07-21 14:43:05 ERROR (MainThread) [homeassistant.components.automation.new_automation_2] Snapshot_TEST: Error executing script. Error for call_service at pos 1: Error rendering data template: UndefinedError: 'entity_id' is undefined
2022-07-21 14:43:05 ERROR (MainThread) [homeassistant.components.automation.new_automation_2] Error while executing automation automation.new_automation_2: Error rendering data template: UndefinedError: 'entity_id' is undefined```
The concept is working on my old installation but now when migrating to a less FUBAR installation it refueses to work π¦
this works on old installation
- entity_id: camera.house_mainprofile
file_out:
- "/config/www/{{ camera_entity.split('.')[1] }}_latest.jpg"
- "/config/www/images/{{ camera_entity.split('.')[1] }}_{{ now().strftime('%Y%m%d_%H%M%S') }}.jpg"
thanks, but that renders True if the payload is 'on' and False if payload is 'off', check```
{% set value = 'off' %}
{{ value if bool(value,none) is boolean else none}}
{{ value|bool(none)}}``` to see how that differs
it renders all mqtt sensors unknown.
also, I read your posts about changing payload, but its not for me to change that, its what the source publishes, so I am following that
but just to be sure, I tried what you suggested anyway. Unfortunately that renders 'unknown' too, so there's no choice in the payload.
This also works π
{% set items = ['a', 'a', 'd', 'a', 'c' , 'b', 'b', 'a', 'd' ] %}
{% set ns = namespace(most_common={'item':none,'count':none}) %}
{% for item in items | unique %}
{% set cnt = items | select('eq', item) | list | length %}
{% if loop.first or cnt > ns.most_common.count %}
{% set ns.most_common = {'item':item,'count':cnt} %}
{% endif %}
{% endfor %}
{{ ns.most_common.item }}
As Tinkerer already mentioned {{ entity_id.name}} is not valid
I might just add a mode filter
more filters, more fun is what I always say
alias: Snapshot_TEST
description: ''
trigger:
- platform: state
entity_id:
- binary_sensor.camera1_person_detected_2
- binary_sensor.camera1_motion
to: "on"
action:
- service: camera.snapshot
data:
entity_id: camera.camera1
filename: www/images/{{ now().strftime("%Y%m%d-%H%M%S") }}{{ trigger.to_state.object_id }}.jpg
``` Try this π
Hey all π question about input Boolean, so itβs kinda switch that gets flipped when the event happens, and then can be used in an automation. Ok so I got that far ( thanks @ Rosemary Orchard#7195 ) Iβve added the toggle in helpers menu. But like how to add info to it ? How to work with it ? In helpers section I could only add two things, name and iconβ¦
If that helps the first thing is to get it to toggle when a device tracker enters a zone
You can manually toggle it, or toggle it in an automation to indicate something happened
So i have to create automation with it first ? so its like an empty shell, and only then i can use it in the main automation ?
It's not related to #templates-archived though
Well, if you want to automate something with it, I guess #automations-archived
I guess yeah
Not that there is much to understand, it's a toggle which can be on or off and will do nothing on its own
Well I thought itβs like a ready to use toggle, and I didnβt knew that I have to make an automation to use it π that was the problem here π
Anyone has a template that sends a notification every time any of the moisture sensor i have triggers?
Seems, more of an #automations-archived thing. If you use a state trigger you can use {{ trigger.to_state.name }} to get the name of the entity which triggered the automation
Moving it
Will do thanks! π
2022-07-22 11:19:39 ERROR (MainThread) [homeassistant.components.automation.snapshot_test] Snapshot_TEST: Error executing script. Error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'
2022-07-22 11:19:39 ERROR (MainThread) [homeassistant.components.automation.snapshot_test] Error while executing automation automation.snapshot_test: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'```
@simple edge :
{% set val= {"living_room": 10, "family_room":17} %}
{{ val["family_room"] }}
Did you manually trigger the automation yourself by pressing Run actions
i did a manual tricker and just read the a thread a bout manual triggering π
so just putting on my outdoor feet to test it out π
there is no no trigger then, so the trigger variables are not available
Works like a fucking charm π
thanks a milion!
Hi, all! I am using the Met.no Nowcast integration for weather, and defining a sensor for temperatureand humidity is working fine using
state_attr('weather.met_no_nowcast_buskogen', 'temperature').
Now, I want to define a sensor telling me if itΒ΄s any precipitation going on, but as you see below, this value is listed in an other way. How would i read values under the forecast: section?
temperature: 15.1
humidity: 91
...
precipitation_unit: mm
forecast:
- temperature: 15.1
precipitation: 4.5