#templates-archived
1 messages · Page 117 of 1
the templating system isn't aware of "who" is doing things
So I can't make a "Welcome {{ user.username }}"-thingy on my dashboard, without getting this parsed to the templating system somehow?
not in the templates we talk about in this channel
there might be a custom card that can do something
but that's more #frontend-archived
Any change explaining how I can become this. Battery greater than 60% green, between 30-60% orange and below 30% red. Thx in advance
Yeah, I don't won't a plugin just for that 🙂
Thank you, I'll think in other ways.
are templates the way to go for logging the amount of coffee my coffee machine makes a day?
Thank you very much. :)))))
this works
{% set d = {
"state": states.light.ge_14294_inwall_smart_dimmer_level.state,
"attributes": dict(states.light.ge_14294_inwall_smart_dimmer_level.attributes)
} %}
{{ d|to_json }}
lets brainstorm: 🙂
what kind of maschine?
will u press one button for every coffee?
its a rest based coffee machine that can make upto 12 cups per time it's run
lol discord hicup
@subtle shore i subbed in an entity i had to repro. you can swap that back with your trigger.x and it should work
i thought so.
but at first = copy and replace with my entity. 😛
yeah, you don't need the whole thing
i just split it out that way to make testing easier
so atm i got an initial json payload.
but if i start a playback the script fails
and easier to read on the tiny template tester box
Object of type datetime is not JSON serializable
ahh you have a datetime in there
that's odd. not casting for the JSON. neat
@subtle shore posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Wn55xh9qXJ/
ahh. damn+
hmm, i need something with a timestamp
I have that shit from yesterday that makes a timestamp
let me scroll up
{% set time_sz = "2021-01-17T01:03:55+00:00" %}
{{ strptime(time_sz, "%Y-%m-%dT%H:%M:%S%z") }}
oh, I misunderstood you before.
can't namespace hack it either
I wonder if adding filters is supported by custom_components, probably not
Nope
quits googling
no, that's managed by core/homeassistant/helpers/templates.py
thanks
I've never actually looked into it but whatever they've done to lock down the functionality of Jinja, I doubt there's a quick hack to add stuff back in.
i cant even get a valit time/date format for my payload alone? o.O
i can't find a way to get down to those values
probably have to build that dict out manually unfortunately
and it has to be done all at once since you can't modify a dict after it is created
so - lets build a python script.
my first at all. 😛
There's a first time for everything. Good luck.
# python3 ./python_dict_to_json_dict.py "{'state': 'paused'}" "{'attributes': {'volume_level': 0.66, 'is_volume_muted': False, 'media_content_type': 'video', 'media_title': 'Test Video', 'media_album_name': '', 'media_series_title': '', 'media_season': -1, 'entity_picture': '/api/media_player_proxy/media_player.livingroom_libreelec?token=XX&cache=XX', 'supported_features': 186303}}" "homeassistant/indoor/debug"
{"state": "paused"}
{"attributes": {"volume_level": 0.66, "is_volume_muted": false, "media_content_type": "video", "media_title": "Test Video", "media_album_name": "", "media_series_title": "", "media_season": -1, "entity_picture": "/api/media_player_proxy/media_player.livingroom_libreelec?token=XX&cache=XX", "supported_features": 186303}}
homeassistant/indoor/debug
seems fine for that
Easy with the code walls...
well. i have to start somewhere
That's... what I said.
yeah, could definitely do it in python
but you can't import json no?
i don't remember the limitations of python_script
correct, you can't do imports on python_script
oh. i didnt saw that. i only saw your disappointment about my script walls - understandably.
@subtle shore Discord isn't like IRC, you don't have to tag people on every response. Keep in mind that every time you tag somebody, they get a notification ping. That can very quickly become annoying and people may block you.
When using Discord's new Reply feature it defaults to pinging the person you reply to, click @ ON to @ OFF to stop this - on the right side of the compose bar.
you can do imports on python_script, I have several that do, one being import json
i think i got it - til the mqtt.publish part. i use pyscript
is someone able to tell how i insert the variable service_data into this: mqtt.publish({service_data}, retain="false" )
translate python dict to json dict was not that hard at all. its actually 4 lines of code.
but i dunno if i can call that script as imagined. will see that.
hi,
i saw the template {{ user }} in the markdown card to pass the username of the logged in user. is something like this possible for scripts?
No
Trying to get Aqara Cube's Side, when I read state of the sensor, it's
<template TemplateState(<state sensor.aqara_cube_action=; action=, angle=-23.71, battery=62, linkquality=131, side=1, voltage=2935, friendly_name=Aqara Cube action, icon=mdi:gesture-double-tap @ 2021-01-19T22:24:44.618917-05:00>)>
Any ideas on extracting the "side"? states.sensor.aqara_cube_action.side does not work
can't get this to work https://i.imgur.com/xPATEja.png
{{ state_attr('sensor.aqara_cube_action', 'side') }}
please review the template docs
Got it!
hi i need help getting a time template to work. the as_timestamp function is returning none
Share your template please
{{as_timestamp(now()) - 30*60 >= as_timestamp(strptime(states('input_datetime.work_day_alarm'),'hh:mm'))}}
ok i have no idea what the ❌ means
anyway the first half befor the comparison works
what returns states('input_datetime.work_day_alarm') alone?
and the strptime works (i think but the dev tools dont actualy say the data type)
a time string
i think
just time ? no date ?
that's why it doesn't work. as_datetimeworks on datetime only, not on time alone
you can't compare a date time (left part of your test) with a time alone
i am not using as_datetime
sorry, I meant as_timestamp
yes
Try something like this : {{as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm'), "%d/%m/%Y %H:%M:%S"))}}
that works but something it is doing is messing up the time zone so it is returning utc time
You can try something like this?
{{as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm')~" +04:00", "%d/%m/%Y %H:%M:%S %z"))}} to add an offset of 4 hours
Or
{{as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm')~" CEST", "%d/%m/%Y %H:%M:%S %Z"))}}
btw is ~ a string join?
yes
+ can also works, but ~ force the conversion to strings, where+ doesn't, reason why + can fail in case of concatenation between strings & numbers
How can I check if a certain state entity is in a certain group?
I tried to expand an entity in combination with my group, and look at its length, but that doesn't seem to do the trick...
ok so the first one did infact work i was just converting to normal time with a converter that did not understand time zones
ok so my full template is this {{as_timestamp(now()) >= as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm'), "%d/%m/%Y %H:%M:%S")) - 30*60}} the intent is to have a trigger half an hour befor a time helper
the problem is i have 2 time helpers so they way i have it set up is that the automation goes off at 4am (because i hope that is befor my alarm) but i want to have this dynamic as well. is there a way to have a template to trigger it say 35mins befor the earlier of the 2 times?
read some time back on this channel that you can do this:
{{states(trigger.to_state)}}```
but it gives some vague error" ` AttributeError: 'dict' object has no attribute 'lower'`
not only in the template developer tool but also when working with real triggers in an automation
so, states() doesn't work for trigger? how else can I cleanup trigger data that might not exist ( triggered manually, triggered by trigger that doesn't support the attribute like sun not having an entity_id etc. )
Hi, for templating value (eg. to show in the gauge card rounded value) the only possibility is to make another entity? Is there no option for customizing existing one entity or better, customizing just the displaying in the card value?
customizing an entity doesn't change it's value, so yeah you have to make a rounded entity. Maybe some custom cards can do this, not sure
Where did you saw that? states is a function that takes in parameter a string representing the id of an entity. I don't see how this could work.
in this channel let me look it up
if you want the state of the to_state of a trigger, just use trigger.to_state.state
I get that. but if for instance entity_id doesn't exist ( for instance for the sun trigger) the automation trows an error, and I want to make it errorless
Sorry I don't really understand. If you want another automation that will trigger 2 hours earlier the first one, just make the same trigger but with a different offset. But I guess I'm missing something
sort of
Ok but in the given exemple, trigger.entity_id returns a string, which is the id of an entity. It is not an object/a dict
basicaly what i want to do would be easy with 2 automations but i want to just have one so i basicaly want to trigger 35mins befor the earlier of the 2 time values
well yes you can do that. In the template it is easy to just select the earlier of 2 time values, and to just use it in your existing template
yeah, I understand that. I want to add some debugging and use notify, but since some of the triggers don't have all trigger atributes I keep getting errors in the log and no debugs to troubleshoot why the conditions in the choose don't match the triggers.
ok thanks now i just need to work out how to chose. can templates handle ternary statements?
What do you mead? templates can have as many lines as you want
https://pastebin.ubuntu.com/p/5JgnbqvhzQ/ the automation in question 🙂
it is a short form of an if statment
oh ok, like this ? {{ "on" if my_var == "abcd" else "off" }}
you will have to test rather trigger attribute exists or not before testing it, to make sure not to break your templates
condition ? true : false
=
if (condition) {
true;
} else {
false;
}
yes, what I wrote is jinja version of it
i have this in there 4 times
yes of course !
{% set my_var = as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm'), "%d/%m/%Y %H:%M:%S")) %}
if you mean defining a variable across your automation (and not only within a template), you can use https://www.home-assistant.io/docs/scripts/#variables
but it can't be used in trigger:, only in action:
and you can use templates to define variable too 😉
ok thanks
im starting to think i realy should just split this into 2 automations
now that i have some other stuff worked out it would not be that hard
can someone help me create a sensor template, that is on when state of other sensor > 15 and off if else?
I tried: value_template: "{{ is_state('bsensor.kantoor_schakelaar_pc_power', '> 15') }}", I think this code is not correct
correct
you can only check with is_state for a exact match
you should try value_template: "{{ states('bsensor.kantoor_schakelaar_pc_power' ) >15 }}"
edited, typo, should be states() not state()
Thanks, I have this code, but it gives unavailable:
- platform: template
sensors:
kantoor_pc:
friendly_name: Kantoor PC
value_template: "{{ states('sensor.kantoor_schakelaar_pc_power' ) >15 }}"
if you input the template part in developer tools > templates what do you get?
I suspect TypeError: '>' not supported between instances of 'str' and 'int'
in that case make it: "{{ states('sensor.kantoor_schakelaar_pc_power' )|float >15 }}"
that seems to work!
I do notice that the state will be 'True' or 'False'. If I want it to be 'on' or 'off' should I instead create a binary_sensor template?
It won't be 'True' or 'False'. It'll be True or False.
no that's the same status
The boolean values True and False are equivalent to on/off.
But in general, if you're creating something binary... yes, you should use a binary sensor 🤯
well since he didn't show the template domain I couldn't tell but like mono says, put it under binary_sensor: not sensor:
Yes, that's the problem with people only sharing half the information 🤣
thanks!
hi, iam not 100% sure if iam right here but here is my problem
is there a way to interpolate this sensor here https://imgur.com/a/rYWrKSX with a template?
i want a higher sampling rate
In a template you only have access to the current version of an entity. So I don't see how you could do that
Maybe you can force a refresh of your sensor more frequently? but indeed, it is not a #templates-archived question
mhh tricky..
its the sun.sun component so i guess its not possible to force the sensor anything
You can by calling homeassistant.update_entity service
mhh iam going to try that
Hi folks. I've created a template sensor with the following template:
{{ states.persistent_notification | count + states("sensor.hacs") | int + 1 }}
{% else -%}
{{ states.persistent_notification | count + states("sensor.hacs") | int }}
{% endif -%}```
In my testing, I see that the sensor updates just fine as new persistent notifications come in, but not as they are dismissed. What's weird is that the template seems to update just fine in both cases when I test it in the Developer Tools view. Is there something that I'm just doing wrong?
the service call does not update the attribute...
as elevation is used here
? The update_entity updates the whole sensor, and therefore the attributes as well, no ??
maybe...
super weird that the sensor updates less the more the attribute value decreases
maybe i should create a sensor by myself....
next sunrise and next sunset are available in the sun.sun component so something similar should be possible
Why do you want more resolution?
i am building my own circadian/adaptive lighting automation as I don't want to use the custom components
the sun.sun sensor updates every ~ ten minutes if elevation is lower than -20
which is way to low as I want to adapt my lights every minute
forcing an update isn't going to cause it to recalculate. And in order to do interpolation, you need to grab historical data. You either need to use a custom_component or dive into the database itself. Your other option is to do the calculation yourself. Seems like alot of work for no net gain when you can just use the custom component.
yup, it's a bit of work. i will try to calculate the curve with the sunset and sunrise values. let's see how this will turn out.
i don't want to have the exact same behavior as circadian/adaptive lighting components. i want to have constant color temp and brightness throughout day and night and only adapt between night and dawn /dusk and night
let's see how this will turn out
if it fails then I will have learned something at least
so use the custom compontent and dump the values to a MQTT light or a template light with input helpers and use the values when you need
very simple to do, and an easy configuration.
Any way to see if an entity is part of a group? I tried comparing {{ expand('group.alerts', 'input_boolean.inputbijk') | length }} and {{ expand('group.alerts') | length }}, but they are the same (input_boolean.inputbijk is not part of the group)
{{ 'input_boolean.inputbijk' in state_attr('group.alerts', 'entity_id') }}
👍🏼
Hello, the template fails because only 'color' or 'white' is sent in the payload. Can someone add if then else syntax or solve another way please? Thanks
data:
color: '{{ trigger.payload_json.color | int }}'
white_value: '{{ trigger.payload_json.white | int }}'
entity_id: light.test
i learnt a trick from someone here to use max function but that seems longer and unclean
"It is advised that you prepare for undefined variables by using if ... is not none or the default filter, or both." ... how would this go?
thanks, looking at jinja now .. but better still how do i use the 'if ... is not none' syntax?
thanks . thing is i dont want to set a default value.., I want only the 'color' OR 'white' data to be applied
the light cant handle non valid value so I cant just send a null value. and if a send a default value it overwrites the existing value
I don't think you can do what you're asking. The properties provided get validated... so you must provide a value entry with either color: or white_value:. You can template the values but not the property names.
hmm... thats a shame. was hoping to put in an if not none on each of the data attributes
send the previous value for the one that isn't changing
Why do you need to have a single thing that knows what to do? If this is for an automation, you should use a choose:
choose is hawt
yeah had that in mind or to create yet another condition / choose and call the service twice. but these methods increase overhead and the esp lights are only slow to react
Hi! I'm not sure this is a templating problem, but maybe related (There's no scripts channel): In trying to create function-like scripts that take parameters, how do I provide and then make use of a provided parameter? The scripts docs say that you can pass the service.script_name call a message with a data attribute, but I don't know how to access that data inside the script? Or am I wrong trying this with scripts and rather have to learn about templates? (haven't looked at them much). My use case: create an Alexa notify function that takes different to-be-announced messages.
ah, thanks! i was looking under https://www.home-assistant.io/docs/scripts/ and there one cannot find this page.
will it work to use == in a time based template or will it never be true because it only triggers every min so i is never exactaly equal?
eg ```yaml
{{as_timestamp(now()) == as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.non_work_day_alarm'), "%d/%m/%Y %H:%M:%S")) - 30*60}}
Hi folls. First time using discord so please redirect me if this is not the place to post ..
I have home assistant on a raspi using the hassio image (not supervised)
I want to play some wav files on different events
I used the ssh addon to access the shell and used aplay there to get sound over the raspi jack (worked)
I used shell_commands in the configuration.yaml file to expose the aplay to the automations (didnt work, HA cannot find the file)
I created a sh file that calls "aplay myfile.wav", executed from ssh, works.
Execute from the "execute a command" in home assistant > file editor (addon) y says it cannot find aplay
I even copied aplay from /usr/bin to /config and called this copy from ssh, works
when executing it from "execute a command" now it can find aplay (the one I copied to /config ), but it complains "aplay: line 16: syntax error: unexpected word (expecting ")")"
How can I get the aplay (or any other sound player) to work from home assistant ???
that is what i had but that means it is true for the rest of the day so it is trigering when it is not meant to
no. HA will trigger only when the trigger becomes true
"When any of the automation’s triggers becomes true (trigger fires), Home Assistant will validate the conditions, if any, and call the action."
ok i have worked it out
befor all the false triggers in the logs there is also a log of the automation being turned off
but no log for turned back on and i did not turn it off
does editing an automation in the UI cause a reload of the full automations.yaml and their for a refresh of all automations that would mean when the automation turns on the template is true for the first time?
I actually don't know that
ok thanks
Hi, there! I am to make a template to show state of a sensor, but would like to exchange on and off states with på and _av, which is the Norwegian equivalent. I only need it in this template (not aiming to go via Customize .
Here is the template I want to change.
Help is highly appreciated 🙂
{{ trigger.to_state.attributes.friendly_name }} måler {{ states.sensor.pir_ute_paviljong_luminance.state}} lux. Setter Grunnbelysning {{ states.binary_sensor.dark_inside.state }}.
... and it´s the states.binary_sensor.dark_inside.state that report the state i like to change
What's the template for? If the language only matters in the UI, then really you should be fixing it in the UI.
If you really want to do it the template way...
{{ 'pa' if states('binary_sensor.dark_inside') else 'av' }}
Never use states.domain.entity_name.state if you can help it. The states() function is safer.
@earnest cosmos ☝️
The template is only used in a notify message. The entire template evaluates to the message string.
Gotcha. Well there's a solution above (minus the Norwegian characters I can't type) 🙂
Thank you, @ivory delta 🙂 👌🏻
I can't get this to work, and I'm probably doing it wrong 🙂
What I would like this automation to do is:
- Run after each state change
- Check if the entity that triggered the change is in a certain group
- Check that the entity is
off
If this is all true, I want to do something with the entity ID. For now, I try notifying my phone, to see if I can get this right, but I don't get any notification...
Oh, I think I need to do this in #automations-archived ...
Little help with templates please. I need to form a dynamic text for TTS . Here is how I get the person name. https://paste.ubuntu.com/p/MrnTNfKYDn/
And greeting message. https://paste.ubuntu.com/p/P5mSW6R9NM/
But the test for greeting message depends on the person name. If it is female some words are different.
and on what part do you need help?
{% set gender = {'male': 'hey dudes', 'female': 'hey ladies'} %}
{% set greeting = {'name1': gender['male'], 'name2': gender['female']} %}
{{ '{} This is an alert!'.format(greeting[person]) }}
Makes sense. Thank you. Arrays in Jinja... Jeez.
Bit overcomplicated. Can't I do if/else/endif between string? Like: if person = X then "male string" else "female string"
this is less complex than that
and if you ever add more people, this is easier to expand
There will be more string that are different.
then change the structure of gender
.format(greeting[person]['intro'], greeting[person]['middle'], greeting[person]['end'])```
{% set welcome = {'name1': 'dobrodošel', 'name2': 'dobrodošla'} %}
{% set hello = {'name1': 'pozdravljen', 'name2: 'pozdravljena'} %}
welcome[person] ~ "nazaj doma " ~ person ~ ". hello[person] ~ spet doma."
I now have like this.
No error.
Different string per different person.
if that's al you're doing, why not just hard code the full thing and just drop in the string for the person?
Eh. Not working. hello[person] is not parsing.
{{ '{} nazaj doma {} {} spet doma'.format(welcome[person], person, hello[person] }}
oh... python print formatting... nice!
yeah, no fstrings though 😢
Hi guys, hope someone can help with a template sensor. I have a sensor called sensor.river_ultrasonic and want to make a new template sensor that takes 0.72 and deducts whatever value is coming from sensor.river_ultrasonic
(Its calculating the depth of a small stream in the garden)
Heres what I have but it doesn't return the correct value
`#River Depth Template
- platform: template
sensors:
river_depth:
friendly_name: 'River Depth'
entity_id: sensor.river_depth
value_template: "{{ states('sensor.river_ultrasonic') | int - 0.72 }}"
unit_of_measurement: meters`
entity_id in template sensors are no longer supported
-0.72 gets returned as a fixed value. Sorry - I'm not too good at the template stuff, I was trying to rehash an example I found on the forum
Thanks for that! It didn't seem to make a difference in or out
what is the value of that sensor and what is the math you actually want to apply?
Currently it is reading 0.43meters. I want to have 0.72 as a fixed integer and subtract the value of sensor.river_ultrasonic from it
0.72 minus 0.43 = 0.29
So the template sensor would be reading 0.29 meters now.
does it actually say meters in the state? If so you'll have to strip it out, or if the number is in attributes you can grab it from there
Yes - that comes from esphome and its just an ultrasonic sensor. I haven't defined meters anywhere for the physical sensor.
what do the attributes look like
go to
> templates and do
{{ states('sensor.reiver_ultrasonic') }}
what is the output?
Result type: number
0.49
seem slike you just have your math backwards then
unit_of_measurement: m
friendly_name: River Ultrasonic Sensor
icon: 'mdi:arrow-expand-vertical'
If I reverse it I just get an error.
{{ 0.72 - states('sensor.reiver_ultrasonic')|float }}
Got it along with making it a float @thin vine - thanks to you all, really appreciate it @brisk temple @dreamy sinew
Sorry phnx, can I use round in conjunction with this to keep it at 2 decimal places? adding round(2) messes the value
I was going to ask that exact question
I always wrap things like that in () but won't now
Then I get AttributeError: 'float' object has no attribute 'lower'
"{{0.72 - states('sensor.river_ultrasonic'|float)|round(2) }}"
because you didn't do what i demonstrated
You are right, my apologies. Got it thank you. Had to run a 50m ethernet cable down the garden in the UK rain to get this sensor on 😩 - one of those days. Thanks again
"{{ (0.72 - states('sensor.river_ultrasonic')|float)|round(2) }}"
how do I render a list from an if-template?
(according to google it doesn't work, but that was before templates strictly rendered strings)
need more context
Theoretically:
{% if ... %}
{{ [1,2,3] }}
{% endif %}
works, it depends on what you need...
what I tried```
{% if is_state('device_tracker.dd', 'home') -%}
[["text1", "/btn1"], ["text2", "/btn2"]]
{%- else -%}
["text2", "/btn2"]
{%- endif %}
oh with braces?
list of lists? seems odd
weird
ye
yeah, need to do a "print" statement
thats how it eats its "keyboard"
{% if is_state('device_tracker.dd', 'home') -%}
{{[["text1", "/btn1"], ["text2", "/btn2"]]}}
{%- else -%}
{{["text2", "/btn2"]}}
{%- endif %}```
{% %} logic statements
{{ }} print statements
ahhh @dreamy sinew
ehh too many values to unpack (expected 2) 😩
Ok. I don't know why or how it works, but after trying forever, this ended up working for some reason. a bit ugly
{% if is_state('device_tracker.dd', 'home') %}
Text1:/btn1,Text2:/btn2
{% else %}
Text2:/btn2
{% endif %}
no list somehow works
Sorry for disturbing and thank you for your help anyway 🙂 🤝
hi i want to know how much energy i have left
Solar - used power =
binary_sensor:
- platform: template
sensors:
netpower:
value_template: '{{(states.sensor.alex_energy_today_kwh.state | float ) - (states.sensor.electriciteit_verbruik_per_dag.state | float)}}'
unit_of_measurement: 'kWh'
friendly_name: Net Power
i tryed but i have error
[unit_of_measurement] is an invalid option for [binary_sensor.template]
i'm i doing this correctly i just want to know how many kWh i have left on a day for as far i know the numbers
or do i just have to remove the united_of line?
well, you're trying to do math in a true/false
you're using the wrong integration
hm
oh ok
i guess it should be sensor:
have no errors in config now tx
stupid of me 🙂
maybe some small thing more
it shows now -14,745999999999999 kWh
and i have set this do i do it wrong for less after the , ?
value_template: '{{(states.sensor.alex_energy_today_kwh.state | float ) - (states.sensor.electriciteit_verbruik_per_dag.state | float) |round(5)}}'
as is, you're only rounding the 2nd number
order of operations says that the | are processed 2nd
hm i just want to have the total rounded
need to wrap the whole thing you're rounding in ( )
PPEMDAS
Paren, Pipe, Exponents...
as is, this is the only bit being rounded:
(states.sensor.electriciteit_verbruik_per_dag.state | float) |round(5)
i think for the most correct use i only have to round the outcome of the -
the total i mean
so you need to group everything together before the round filter is applied
hm
maybe place an extra ( inhere
'{{((states.
and end with a ) more
|round(5))
thats not working to pf
value_template: "{{ ((states('sensor.alex_energy_today_kwh') | float ) - (states('sensor.electriciteit_verbruik_per_dag') | float))|round(5) }}"
hm nice
i think i was almost there
many thanks !
i really needed this thing
belgium is fucked up with their digital power meter
normally the disk turns back now suddenly they quited that
works
{{not is_state(states.media_player.avr_zone1.state, 'off')}}```
first is off, and why Im getting true for second one
because you're reversing the result with the not
oh wait
oh, because you're using is_state() incorrectly
check the docs for the proper usage
Any way to simplify this?
data_template:
entity_id: >-
{%- if states.binary_sensor.workday_sensor.state == 'on' and states.input_boolean.vacation.state == 'off' and states.input_boolean.company.state == 'off' and states.calendar.holidays_in_norway.state == 'off' and states.calendar.work.state == 'off' -%}
script.morning_lights_weekday
{%- else -%}
script.morning_lights_weekend
{%- endif -%}
Using is_state() could help some but that's about it
👌🏻
Or you could add a template sensor to do those checks and use that in your automation instead
You mean defining each of the if/else statements as separate template values?
No, create a template binary_sensor that evals that template and then you just key off of the one value for your automation
got it. Thanks
.. and could this
condition:
- condition: template
value_template: "{{ states.binary_sensor.garasjeport.state != 'off' }}"
Be simplyfied to this?
condition:
- condition: template
value_template: "{{ is_state(binary_sensor.garasjeport]' }}"
Gotta provide a state
Not this either? "{{ states.binary_sensor.garasjeport.state }}"
You should review the template docs
I was looking for a way not to include the !=, and have been playing by the book/doc. now I just was imagening it wold work in a more simple form.
I stick to the original then. It works... 😉
Trying to debug a template to pull from ecobee using Developer Tools. Going well. So I've got {{ states.climate.home }} and the output is this :
<template TemplateState(<state climate.home=heat; hvac_modes=['heat_cool', 'heat', 'cool', 'off'], min_temp=7.0, max_temp=35.0, fan_modes=['auto', 'on'], preset_modes=['Home', 'Away', 'Sleep', 'Telework'], current_temperature=22.9, temperature=23.0, target_temp_high=None, target_temp_low=None, current_humidity=28, fan_mode=on, hvac_action=fan, preset_mode=Home, aux_heat=off, fan=on, climate_mode=Home, equipment_running=fan, fan_min_on_time=40, friendly_name=Home, supported_features=91 @ 2021-01-21T11:59:40.647605-05:00>)>
Fan <template TemplateState(<state climate.home=heat; hvac_modes=['heat_cool', 'heat', 'cool', 'off'], min_temp=7.0, max_temp=35.0, fan_modes=['auto', 'on'], preset_modes=['Home', 'Away', 'Sleep', 'Telework'], current_temperature=22.9, temperature=23.0, target_temp_high=None, target_temp_low=None, current_humidity=28, fan_mode=on, hvac_action=fan, preset_mode=Home, aux_heat=off, fan=on, climate_mode=Home, equipment_running=fan, fan_min_on_time=40, friendly_name=Home, supported_features=91 @ 2021-01-21T11:59:40.647605-05:00>)>
But if I eval {{ states.climate.home.equipment_running }}, nothing is output.
Okay I got it - value_template: '{{ "fan" in state_attr("climate.home", "equipment_running") }}'
Similar to @sage aurora I'm just looking at getting the climate info into a template sensor. I'd sorted how to get an actual named attribute out. What I can't get is the current "master" setting? In the above example I'm trying to get the "heat" answer, where it says the state is: state climate.home=heat;
(although I live in AU so mine will say "cool" right about now 😉 )
ok that turned out to be easy.{{states('climate.daikin_ac')}}
the state_attr() is the better way, but in case you wonder, this is how to make the other way work {{ states.climate.home.attributes.equipment_running }}
better because it catches any errors because of unavailability etc.
Morning all! I'm trying to get "custom" attributes using json templates from an MQTT message, i.e. format them and give them a custom name this is what i have tried any ideas? https://paste.ubuntu.com/p/nvBzGvS73z/
And what's the result of that? In value_template you have is_state(entity_id,\"on\") but entity_idis not defined.
the trigger and sensor it self work perfect, just the attributes, entity_id in this case is self referential i believe: https://imgur.com/1UZgdvN
I guess it should be 'sensor.hall_motion_camera'
Yep me too when i found it 🙂 just trying to sort out the attributes, will also be useful in rest sensors and such
did you test the template in the dev tool?
it says 'timestamp_local' is undefined
I suggest using strptime to parse the date string in a date object
i shall remove the timestamp formatting for now, and do a restart, mostly concerned about getting the attributes layed out 🙂
{{ {'Last Motion': '~strptime(value_json.currentTimestamp, "%Y-%m-%dT%H:%M:%S%z")~', 'Motion Area': value_json.details.name, 'Timestamp': value_json.currentTimestamp } | tojson }}
ah ha! yes okay that does work (pre-timestamp formatting): https://imgur.com/ewCLpQU
fyi you do not need to restart for that. If you are already in advanced mode, you can just relead MQTT entities
ooo yes there is a button for that, used to having to reload for rest sensors and such!
got "TypeError: Object of type datetime is not JSON serializable" on that one
yes you have to create a string out of the date you created with strptime. So either you keep the initial date string or you use strftime to format the datetime with whatever format you want
{{ {'Last Motion': strptime(value_json.currentTimestamp, "%Y-%m-%dT%H:%M:%S%z").strftime("%Y-%m-%d %H:%M:%S"), 'Motion Area': value_json.details.name, 'Timestamp': value_json.currentTimestamp } | tojson }}
It's so... pretty
why is something like this not possible? https://pastebin.com/KnjCBC2Y
or how can i get this to work?
I believe because you use target instead of entity_id. Target I think is only for blueprint targets if I remember correctly
I see. you seem to be wanting to make list, but currently you are making a string, maybe one of the template guru's here can give a good way to do it in this case.. I'm struggling with that part still
i hope so. iam struggling there too. jinja templates are still hard. would really like to see some advanced tutorial in combination with HA
There are guides in the topic here, and Jinja itself is well documented on its own site.
https://jinja.palletsprojects.com/en/master/templates/#literals : ['list', 'of', 'objects'] Everything between two brackets is a list
but iam lost on how to do the if query with that information
{%- if is_state('binary_sensor.wz_besetzt','on') and is_state('binary_sensor.ku_besetzt','off') %},{%- endif -%}
{%- if is_state('binary_sensor.ku_besetzt','off') -%} media_player.kuche_alexa{%- endif -%} ]``` I think....
hi, I have a sensor (sensor.foo) whose value is a number that is always increasing (once per day or so). I'd like to create another sensor (diff_foo) which is updated each time the first one is updated and contains the difference with respect to the previous value. I saw I can use an automation for that, but I actually want to do the same for like 17 sensors so I'd like to avoid creating 17 automations if possible. What's the recommended way to do that?
ok, thanks. I'll ask there
i will test this, ill have to figure it out how to use more then two media players here
If that's for use in an automation/script, don't even try to handle all the possible combinations in a single template.
Use the choose: block.
I suggest : ```
{% set my_list = [] %}
{% if is_state('binary_sensor.wz_besetzt','on') -%}
{% set my_list = my_list + ["media_player.wohnzimmer_alexa"] %}
{% endif %}
{% if is_state('binary_sensor.ku_besetzt','off') -%}
{% set my_list = my_list + ["media_player.kuche_alexa"] %}
{% endif %}
{{my_list}}
Easier to manage several binear_sensor/media_player
Or
{% set my_list = [] %}
{% set my_list = my_list + (["media_player.wohnzimmer_alexa"] if is_state('binary_sensor.wz_besetzt','on') else []) -%}
{% set my_list = my_list + (["media_player.kuche_alexa"] if is_state('binary_sensor.ku_besetzt','off') else []) -%}
{{my_list}}
yeah much better, hence my hesitation to give a solution
also, what mono says, choose: in automation / scripts is a life saver much better than trying to do everything in templates or a gazillion automations with big conditions
Can anyone see where i am going wrong here ?
red
{% elseif states(config.entity)|int > 29 and states(config.entity)|int < 34%}
green
{% else %}
blue
{% 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://paste.ubuntu.com/ or https://www.hastebin.com/.
And if you don't say what it should do, it's going to be hard to help fix it.
Replace % with /100
and you miss the % for the > 29
it's the % of %}
I was also confused at first
{% elseif should be {% elif
its using Thomas Loven's "Card Mod" for badge customisation https://github.com/thomasloven/lovelace-card-mod
hehe you beat me to it slashback
ok, so just try to apply the fix we proposed
This is a working one FYI ```badges:
- entity: sensor.zeversolar_generated_power
name: Solar Power
style: |
:host {
--label-badge-red:
{% if states(config.entity)|int >0%}
green
{% else %}
red
{% endif %}
;
}```
changes badge colour from green to red
Thanks the elseif --- elif seemed to be the culprit.
choose is not an option here as its not an automation or script
and i want to keep this in the notify integration if possible
hmmm not sure if integrations can use templates in this way and if it will evaluate more then just at startup
if it fails then i will try it with a script and use the fields function for the message. but i will see if i get home 😄
What on earth are you trying to do? Why do you have this weird template in the definition of an integration?
Even if that worked, it wouldn't be updated unless you restart HA...
🤔
i want to send messages from alexa only to rooms that are occupied
i did not know that 🤣
HA loads config. It doesn't monitor config.
All your YAML files are gathered together and loaded and that's it.
So... use a script/automation and use the choose: syntax.
Hi folks!
I'm coding an script and I'd like to ask ho does one check if a variable has been set at all ?
tried with
- condition: template
value_template: '{{if messageTitle}}'
and
- condition: template
value_template: '{{messageTitle == None}}'
nothing works, it always go through the "default" part of the condition
when calling from the dev tools > services, with no data defined
when setting the messageTitle it does apper as part of the message body (as expected) so the problem is not in the variables management
is just the syntax for cheking if set
also tried messagetitle == ''
does not work
also tied just
- condition: template
value_template: '{{messageTitle}}'
nothing . .
oh lord... I cannot find it 🙂
{{ messageTitle is defined == true }}
{{ messageTitle != '' }} should work as well
can it be shorten to just {{ messageTitle is defined }}
!= '' did not work, I tested it to death
prob
value_template: '{{messageTitle == None}}'
when writing this, do you use 'or " around the statement ?
use template editor
hum.. that would has been smart : )
you have to use the opposite of what your wrapping the value_template in
what would be the syntax for and AND in the value template in a Choose statement ?
{{ messageTitle is defined == true && messageBody is defined == true }}
or
{{ messageTitle is defined == true AND messageBody is defined == true }}
none of the mseams to work with jinja thingy
check the link in the pin messages
to help with formatting
{{ messageTitle is defined and messageBody is defined }}
nooooooice
hey guys ! 🙂 can someone explain why inst this working well ?
{% if value_json.price is not number %} Disconnected {% else %} {{value_json.price}} {% endif %}
{{value_json.price}}
result:
Disconnected
1.2245
because of the quotes around the number !
{% set value_json = {"symbol":"ERUSUD","price":1.2245} %}
but value_json.price extracts without the quotes ...
no, it outputs a string
there's nothing to fix? 🤷♂️ either you want it as a string or as a number. If you want to check it's a number, then make it a number. If you want it as a string, stop checking if it's a number.
{%- set value_json = {"symbol":"ERUSUD","price":"1.2245"} -%}
{{ 'Disconnected' if not value_json.price|float else value_json.price }}
but somtimes my rest api is unable to fetch the price , and is my calculation are messing up, i want it to show price when only the price is a number...
Thank you ❤️
Can someone with an Ecobee let me know if they're able to access heating call info? I can pull in the info but I can never see any info.
I can grab my fan call, humidifier call... but the raw info never changes.
Hey, I try to make an automation which create a snapshot, and want it to name the file the date. I using this parameter on the call name: "{{now().strftime('%Y%m%d')}}" but the name on the backup files is just {{now().strftime('%Y%m%d')}}
Can anybody help me understand what i'm doing wrong?
When I test the template in the developer -> template session it is showing the date: 20210122
From what you've said, the integration you're calling doesn't understand templates.
that could be the problem the integration is hassio.snapshot_full
https://i.imgur.com/GHRfmA2.png hvac_action is never anything other than fan. equipment_running will sometimes be fan, humidifier but heating doesn't show up in it.
Thanks
Hey team, quick question: has anyone ever tried to access 'supported_features' to get a list of all the lights with specific features? I can't seem to access that through selectattr.
| selectattr("attributes.supported_features", 'defined')
| selectattr("attributes.supported_features", 'eq', '43')
| join(', ', attribute="attributes.supported_features") }} ```
doesn't seem to work - it shows nothing.
I copied and pasted your exact template and it worked
well I don't think it is accurate, but I got more than nothing
Thanks @timid osprey , but it looks like it hasn't worked. In the field that says "Result type, string", that's where any of your lights that have '43' for their supported_features should appear. But it's blank.
The list below is showing everything it's listening to.
To check it out, try removing the second line:
| selectattr("attributes.supported_features", 'defined')
| join(', ', attribute="attributes.supported_features") }} ```
See what you get back as a list from that.
I just realized what I did before, lol
@solemn patio I think you just need to use an int instead of a string
🤦♂️
You're a legend, @timid osprey! I've been staring at that for hours!
Thank you so much! 😄
no problem
Hi everyone, my mqtt sensor return values in double quotation marks i.e. '"value"'. Is there a way to get rid of the excess marks in some smart way?
Hello! I want to lookup the device/friendly name of a device by a child (entity). Are there any lookup methods I could use?
The background: I've a automation which monitors the binary state of an entity (connection status). The automation shall notify about the device name which is offline. The connection status entities doesn't have a proper friendly name to know which device is offline.
I tried to avoid redundancy here.
hi!
i want to extract everything after the last "_" out of an entity id. can someone point me in the right direction here?
for example input_boolean.living_room_test
i want the output to be "test"
having the entity name, you extract with .split()[]
{{ 'input_boolean.living_room_test'.split('_')[-1] }} returns test
@lofty nymph maybe you could help me out with getting rid of excess quotation marks in '"value"'?
You can use the same approach, assuming there are no quotes inside the string 😉
{{ '"some quoted string"'.split('"')[1] }}
should return the second item in the array that results when you split by double quotes.
You want the second because the split is going to return ['', 'some quoted string', '']
Many thanks mono. That does the job.
nice! didn't know you can do the -1 for last item
It's not a feature of all languages. I've only seen it with Python so far.
Way easier than having to calculate the length of the array first and get the n-1 item.
indeed. my python skills are weak. I do some basic scripting with it now and then, I can adapt other peoples work to suit my own, but not enough to write from scratch
hello, is there a jinja or otherwise syntax that can be used for data of a service which tell the service that the data to be applied should remain unchanged? For example, where hue and saturation are needed for hs_color but only one is supplied? Thanks
hs_color:
- '{{ trigger.payload_json.hue }}'
- leave value unchanged
entity_id: light.test```
@ivory pawn May be the current value is stored somewhere (at the attributes of the entity?) and you can use it again?
@lofty nymph yes thanks, that is possible and the work around but i was hoping for a 'special' value or function that might be put in place of 'leave value unchanged' to make easier coding and readability
You could take a look at the implementation: https://github.com/home-assistant/core/blob/dev/homeassistant/components/light/__init__.py#L110
This line defines a validator which is strict: the list must have two elements. both elements must be float in range of ...
There are no declarations for "is optional" or something like this.
my experience with lights is that not providing the variable ( like hs_color) keeps that one unchanged, unless you change for instance kelvin/temperature which will also change the color. BUt if you just adjust brightness, color will remain the same
Take a look at the example. The user wants to pass the hs_color but just the hue component. He wants to skip the saturation (second component) of hs_color.
ah, hmmm , yeah I misread the question in that case 😉
besides what you already sugested, reading the value from the entity, I don't know of any other way
Thanks @lofty nymph and @thin vine my coding is basic so thanks for looking at that. I guess the work around is only way to go. cheers!
@ivory pawn {{state_attr('light.staande_lamp', 'hs_color')[1]}}
How do I get the last_changed-property for an dynamic entity_id?
{{ state_attr(entity_id, 'friendly_name') }} works well, but the last_changed isn't a state variable. {{ states(entity_id).last_changed }} does not work and making a string like {% set entity = 'states.' + entity_id + '.last_changed %} does just return "None" when I try to output it
last_changed is an attribute, too. {{ state_attr(entity_id, 'last_changed') }} doesn't work?
Oh.
You are right.
It's part of the state_object.
And no attribute.
Yes
You could access the state object directly but I think this isn't as safe as using methods:
{{ states.light.office.last_changed }}
Okay. You are missing the dynamic part. 😛
Now I understand your entire question
Problem is that I only have the entity_id as a dynamic string, so that will just output the string
{{ states['light']['office']['last_changed'] }}
{% set entity = 'states.binary_sensor.' + entity_id + '.last_changed' %}
{{ state_attr(entity_id, 'friendly_name') | replace(' contact', '') }}: {{ entity }}
Just outputs some like:
My Sensor Name: states.binary_sensor.my_sensor_name.last_changed
I see! 😄
It's not elegant but you could replace in this example ({{ states['light']['office']['last_changed'] }} ) the string "light" and "office" by pieces of your entity.
{{ states[entity_id]['last_changed'] }} seems to work 🙂
Good job!
Thank you! 🍺
But be warned: It's possible your Home Assistant logs some error on start-up now.
Because you are accessing some structure before it's available.
If I remember correctly the state_attr() and states() method is some safeguard.
I'll use it in an automation (in a value_template) so I don't think that will be the case here, right?
As the state have already been triggered
If your automation doesn't trigger before your entity is available you should be safe. 😉
👍
Which version of Jinja does HA use?
Okay, I'm almost there with this TTS automation / template I'm trying to build out... this is what I have so far in the template tools:
{% set my_list = [] %}
{% for player in my_players %}
{% if is_state("switch."+ player + "_do_not_disturb_switch", 'on') %}
{{ player }}
{% endif %}
{% endfor %}
which will correctly output show_office as it is set to DnD and the others are not.
I was trying to figure out how to create "my_list" based off the states of those devices but I can't seem to get the syntax worked out how to build a device with a string for that...
trying something like this just as a test: ```{% set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] %}
{% set my_list = [] %}
{% for player in my_players %}
{% if is_state("switch."+ player + "_do_not_disturb_switch", 'on') %}
{{ player }}
{% set my_list = my_list + (["media_player.blahblahblah"]) %}
{% endif %}
{% endfor %}
{{my_list}}```
and "media_player.blahblahblah" never appears in the result
i think there's a scoping issue here, and thats probably my problem...
do i really need to build out an if statement for each device?
yup, definitely a scoping issue, nothing makes it out of that for loop
adding {{my_list}} inside the for loop gets a result
I think you need to use namespace.
What if you use:
{% set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] %}
{% set my_list = namespace() %}
{% set my_list.my_list = [] %}
{% for player in my_players %}
{% if is_state("switch."+ player + "_do_not_disturb_switch", 'on') %}
{{ player }}
{% set my_list.my_list = my_list.my_list + (["media_player.blahblahblah"]) %}
{% endif %}
{% endfor %}
{{my_list.my_list}}
I think you can do that better, but I don't know enough about jinja to know how.
there it is
that makes sense, i was barking up that tree but was missing the second assignment on line 3
seems so obvious now, lol
So it works now? 🙂
I have used quite a lot of these things. For example here: https://github.com/DrBlokmeister/HASS_NUC/blob/master/packages/misc/unavailable_sensor.yaml
yup works great
Nice. Happy to help! 🙂
so, ultimately what I'm trying to do is pop this into a list for notify.alexa_media
{% set my_list = namespace() %}
{% set my_list.my_list = [] %}
{% for player in my_players %}
{% if is_state("switch."+ player + "_do_not_disturb_switch", 'off') %}
{% set my_list.my_list = my_list.my_list + (["media_player." + player]) %}
{% endif %}
{% endfor %}
{{my_list.my_list}}```
Okay, this might be back into the automations topic, but trying to figure out how to use this now for a list of devices. I thought something like this would work: ```service: notify.alexa_media
data:
message: '{{ message }}'
data:
type: tts
method: speak
target: >
{% set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] %}
{% for player in my_players %}
{% if is_state("switch."+ player + "_do_not_disturb_switch", 'off') %}
- media_player.{{player}}
{% endif %}
{% endfor %}
but it is not
not seeing an error anywhere that i can find
What happens when you evaluate the template?
oh
oka
so, it's a string
so, that might be my problem
also, it's all spaced out
is what it looks like
I think then you need to use dashes inside the brackets {%- blabla -%}
ultimately I'm trying to do something like this:
data_template:
message: '{{ message }}'
data:
type: tts
method: speak
target: >-
{% set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] %}
{% for player in my_players %}
{% if is_state("switch."+ player + "_do_not_disturb_switch", 'off') %}
media_player.{{player}}
{% endif %}
{% endfor %}```
{%- set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] -%}
{%- for player in my_players -%}
{%- if is_state("switch."+ player + "_do_not_disturb_switch", 'off') -%}
media_player.{{player}}
{%- endif -%}
{%- endfor -%}
Try that
Ah hold on. You want to send a tts to a lot of speakers?
Maybe that doesn't work. In that case, do you know if it's possible to send tts to a group of speakers? Then you just need to programmatically set a group. I also do that here: https://github.com/DrBlokmeister/HASS_NUC/blob/master/packages/misc/unavailable_sensor.yaml, line 110 onwards.
yeahhhhh
ok
so, basically I'm trying to filter out the speakers that are set to DnD
but, the states of the DnD for speakers aren't attached to them...
so, bascially i'd create a group called "tts speakers" or whatever and populate it with a template sensor?
Ooh. That's a good point. You want the group to be empty... Hmm...
But you cannot create an empty group.
actually
it doesnt need to be empty
i just need to be able to remove objects
when they're dnd
so, that might work even better
Then again, if I look at my file, you should be able to just use the original template, but then do:
{%- set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] -%}
{%- for player in my_players -%}
{%- if is_state("switch."+ player + "_do_not_disturb_switch", 'off') -%}
- media_player.{{player}}
{%- endif -%}
{%- endfor -%}
But you would need to remove some %'s to allow for creation of newlines
ah ok, so with a blank group
I mean, my template group creation does the same thing as what you want, right?
You want to programmatically make a list that reads
- media_player.mancave
- media_player.bdsm_basement
- media_player.killroom
Right?
And parse that to notify alexa.
yup
I do the same thing, but then parse that to group.create.
You should just modify my template to suit your needs and boom! Voices in your basement.
to match the ones in my head, fantastic!
Yeah
Be sure to check an if statement: if {{ not message == safeword }} do nothing
You don't want Alexa to call out the safeword by surprise in your basement.
correct
Oh wait. I just realised that group.set accepts a list of comma separated entities as in input. I don't know if it will still work for notify.alexa.
Basically I have a sensor that detects all unavailable entities. However, I have some devices that have multiple entities. For example if my smart plug is offline, I really don't care about the energy today, current voltage, current power, etc. all being unavailable. I therefore programmatically create a group that contains all those secondary entities if the main device is offline. I think the important part is the automation from line 100 onwards. I basically create a list of entities there and parse that to group.set. That's all.
ohhh
i didnt look down far enough
lol
im like, i dont see how this sensor is doing anything to a group
it helps to scroll...so they tell me
Have you got it figured out now? @sharp night
@sharp night posted a code wall, it is moved here --> https://paste.ubuntu.com/p/C9h4nHdngz/
good bot
that seems to evaluate out to what i want in the template area
2021-01-23 14:50:24 ERROR (MainThread) [homeassistant.components.automation.update_dnd_stuff] While executing automation automation.update_dnd_stuff```
oh wait
word wrapping!
update: https://paste.ubuntu.com/p/9cQYvvz8Rf/ still same error, doesn't look like the line wrapping was the problem.
no
trailing comma
I recommand the following
{%- set entities = namespace(entities=[]) -%}
{%- for entity_id in states.group.base_alexa_announce.attributes.entity_id -%}
{%- set player = entity_id.split('.') -%}
{%- if is_state("switch."+ player[1] + "_do_not_disturb_switch", 'off') -%}
{%- set entities.entities = entities.entities + [entity_id] -%}
{%- endif -%}
{%- endfor -%}
{{ entities.entities }}
it avoids to play with the comma
and it returns a list, which seems to be accepted by the group.set service
thats it
I been switching back and forth between so many ideas. lol
that worked perfect
thanks!
Great
that's working perfect, and i setup my trigger run on the state change on all of those do_not_disturb switches, works like a champ
I've got a dehumidifier that has tank_show attribute as a True/False. Even though it changes to True the bellow template always stays as Empty
{% if is_state('humidifier.midea_dehumidifier_18691697727728', 'tank_show'), 'False' %}
Empty
{% else %}
Full
{% endif %}
Am I being stupid?
I wouldn't say stupid but you are doing it wrong 😄
check out state_attr
is_state is going to check the state of humidifier.midea_dehumidifier_18691697727728, and return true if the state is tank_show
allright i have a bit of weird challenge here, not sure if it's blueprints or templates but i'll start here
working with a blueprint, using a device selector, and that returns a device id in the format 3fde16be76f2758625733f72e25d569f
what i'm trying to do is to turn that back into a friendly_name or similar, using a template
and... well that's as far as i got.
hi all! can someone tell me why this doesn't work?
entity: climate.panelovn_kontor
style: |
:host {
--paper-item-icon-color:
{% set mode = states(climate.panelovn_kontor) %}
{% if mode == "heat" %} red
{% else %} blue
{% endif %}
;
} ```
3 backticks at the end too 🙂
What's the problem/error?
the icon doesn't change color if the state is "heat"
I'd like a red colored icon if the climate unit is in state "heat"
what does it do in the template editor?
i get UndefinedError: 'climate' is undefined
but climate.panelovn_kontor is an entity
in your template editor, try {{ states("climate.panelovn_kontor") }}
note the quotes. i suspect that's your problem.
like this?
{% if mode == "heat" %} red
{% else %} blue
{% endif %}
does it work?
puts out TemplateSyntaxError: expected token ':', got '}'
hmm
thank you for helping me btw 🙂
oh get rid of the nested template too
so instead of {% set mode = {{ states("climate.panelovn_kontor") }} %}
do {% set mode = states("climate.panelovn_kontor") %}
that worked!! thank you so so much!
if i might bother you with another question. how do I check one of the attributes?
state_attr('device_tracker.paulus', 'battery') will return the value of the attribute or None if it doesn’t exist.
if you're using it to test, try is_state_attr('device_tracker.paulus', 'battery', 40)
make sense? first one just returns that attribute, but if you're using it in an if you can save yourself a little typing and use is_state_attr with the test condition. keep that page above bookmarked, you're going to be referring to it a lot 😄
you're welcome, glad you got it sorted!
@mild pulsar posted a code wall, it is moved here --> https://paste.ubuntu.com/p/RxXRZVYQnC/
@mild pulsar posted a code wall, it is moved here --> https://paste.ubuntu.com/p/d7x9Wx5HBq/
Hi, is there a way to make {% set lights = ['light.dining_bulb', 'light.hallway', ...] %} dynamic. So that all light entities are included?
Thanks that will work! Just want to change lights that already on
{{ expand(lights)|selectattr('state','eq','on')|map(attribute='entity_id')|join(',') }}```
seems to work
Overkill
I'm an amateur lol. Just trying to piece together code from different sources 😆
{{ states.light|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}
right.. that looks better! Thanks
Hey All
I keep getting the following two logs, which repeat every minute on the dot. I've loaded a sample here: https://paste.ubuntu.com/p/pnzn8GyxhZ/
I've looked through all of my helpers and can't find AllStates or any helpers that use a template for that matter, so I'm not sure if this is the correct location to post.
I've also running a debug logger (below the logs) and it doesn't give me any more information.
Appreciate any help with this
2021-01-24 15:35:00 ERROR (MainThread) [homeassistant.helpers.condition] Error during template condition: UndefinedError: homeassistant.helpers.template.AllStates object has no element False 2021-01-24 15:35:00 ERROR (MainThread) [homeassistant.helpers.condition] Error during template condition: UndefinedError: homeassistant.helpers.template.AllStates object has no element True
logger: default: info logs: homeassistant.components.automation: debug homeassistant.components.script: debug homeassistant.helpers.condition: debug homeassistant.helpers.template: debug homeassistant.helpers.template.AllStates: debug
Sounds like you have an automation that's triggering every minute and that it have a template accessing the states object directly instead of using states(entity_id)
Does anyone know if it's possible to check if a service exists inside a template or if it is possi le to detect it in any other way either in a template or in an autotomation's condition?
Thank you,
I've found a blueprint with the time pattern below. When I comment out the respective automatons the problem goes away.
`trigger:
- platform: time_pattern
minutes: '*'
condition: []`
Hi everybody! I am trying to declutter and icon template via the decluttering card addon and I have an issue with the icon:
If I put this piece of code in my ui-lovelace.yaml it works
If I do the same via the decluterring card the icon is blank 😦
The issue is for sure located in this line but don't know how to fix it:
${ states['cover.volet_cuisine_level'].state === 'open' ? 'mdi:window-shutter-open' : 'mdi:window-shutter' }
Update: the time pattern was a factor, but the issue was that I was testing a boolean against ''on'' rather than true
{{ 'mdi:window-shutter-open' if states['cover.volet_cuisine_level'].state == 'open' else 'mdi:window-shutter' }} or better even:
{{ 'mdi:window-shutter-open' if states('cover.volet_cuisine_level') == 'open' else 'mdi:window-shutter' }}
since the last one covers better for unavailable states
oops wrong reply to... @bright carbon it was meant for your question
Hey,
I'm still new to the whole template thing and trying to get my head around this.
I'm trying to create a Wunderground Forecast Sensor based on an rest api call.
So far everything is working. I'm trying to link two JSON-Values together.
My Sensor looks like:
pws_forecast_1d:
value_template: '{{ states.sensor.pws_forecast.attributes.daypart[0].daypartName[0] + states.sensor.pws_forecast.attributes.daypart[0].narrative[0] }}'
friendly_name: Wettervorhersage 1D
If I only extra one value everything is working.
Is it not possible to link two values in one sensor?
you can. are these numbers or strings?
Both are String
Thanks @thin vine , looks good...
😩 using HA for almost 3 years now, and still so much to learn...
haha 3 years too. and learning new bits every day as well
and try templates out in
-> template first, that way you get errors early
I did, and there it worked
that's weird
An it even Says it a string
But hey, now it worked. Maybe I'm getting closer to my first "Share your Project" Post in den Forums
🙂
@thin vine thanks for your feedback.
I tried by implementing this line into the decluterring template but still no luck 😦
try it in
-> template first, it should be working there
else something else is wrong, I tried the syntax in my own dev template
{{ 'mdi:window-shutter-open' if states('[[entity]]') == 'open' else 'mdi:window-shutter' }}
Correct, in template it is working
so this is the implementation in the decluterring template which is the issue 😦
Is the external_url stored into a variable, so I can get it in template?
Have tried {{ get_url }}, {{ external_url }}, {{ network.get_url }} ect.
not that I know
how do i actually add a template
That's a pretty vague question. It depends entirely on what you're doing that needs a template.
What Mono says. But maybe if you mean how to implement a template for a certain entity or line, you just write the template behind the entry that you need. So if you want to use a template for an entity id, you should write:
- entity_id: {{ states('input_select.entity_selector') }}
With quotes around it, of course 😉
is there a way to template some data from a Device trigger? something in the vein of {{ trigger.device.model }} ???
https://www.home-assistant.io/docs/automation/templating/
"states[trigger.to_state.domain][trigger.to_state.object_id] will return the current state object of the entity."
with that you can then get attributes from the device, including the model, as long as that is an attribute of the entity
not an entity, its a Device trigger
🤢
states[trigger.to_state.entity_id]
Functionally equivalent and far easier to read. Whoever wrote that example on the docs needs to be shot.
@jagged obsidian one of us is going to find an answer to this problem 😄
just keep trying
my problem is that it isn't even a trigger, so the trigger. approaches aren't going to work
i think noone knows 😄
i think it can't be done, but i'm going to chase it down just in case i'm wrong
it's been known to happen
I see an opportunity to make the docs better there 🙂
Is something like the following possible? set_lights_onoff: alias: Reconfig Lights OnOff sequence: - service_template: > {% for ieee in ['XX:XX:XX:XX:XX:XX:XX:XX', 'XX:XX:XX:XX:XX:XX:XX:XX'] %} - zha.set_zigbee_cluster_attribute data_template: ieee: {{ ieee }} endpoint_id: 11 cluster_id: 768 cluster_type: in attribute: 3 value: 65536 {% endfor %}
Thank you for volunteering. 😁. Yes, i would suggest it needs more examples for non-programmers, real examples like the ones that pop up here. I have found my best docs to be random Reddit threads found by google! (I am a non programmer)
Also as a noob it would seem some things folks use templating for (like button icon / color changes on state change) should eventually be part of the cards function using simpler key pairs in yaml. This would make HA more accessible to more folks. But I dont understand backlog so won’t pretend that this is important now.
i've already made a PR to change that example
This is probably a very noob question. I'm trying to create an automation with templating. Switched the automation editor to YAML view, and pasted this:
description: Test
trigger:
platform: state
entity_id: sensor.ikea_tradfri_switch1_click
action:
service: >-
{% if trigger.to_state.state == 'on' %}
light.turn_on
{% else if trigger.to_state.state == 'off' %}
light.turn_off
{% endif %}
target:
entity_id: light.ikea_tradfri_bulb1_light```
When trying to save it the UI says:
`Message malformed: Service {% if trigger.to_state.state == 'on' %} light.turn_on {% else if trigger.to_state.state == 'off' %} light.turn_off {% endif %} does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']`
It seems it doesn't acknowledge the template and tries to literally use it as a service name? What am I doing wrong? 😐
@desert flume posted a code wall, it is moved here --> https://paste.ubuntu.com/p/WsrF9cvb9g/
2ND statement should be elif instead of else if or just else without de check
wow, that was it. thank you!
yeah sorry, forgot this syntax in Python. 😊
actually templates are Jinja
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
I made a helper (DAYS as a number) . How do i round it of? It shows 3.0 days now. Would like that it shows 3.
How I can check if a variable/field in a script is a list or a single item?
- wait_template: "{{ is_state(output, 'idle') }}"
output would normally be a single media player, i.e. media_player.kitchen, but I want to make the script work with a list of media_player as well, so I can specify one or more when calling the script
@spring zenith if your helper is an entity something like input_number.days, you can use something like {{ states("input_number.days")|int }}
@modest sparrow use the length filter
for example, i can get a count of the number of automations i currently have defined: {{ states.automation | length }}
now that i say that.... if it's a single item instead of the length of the list you get the length of the characters in the single item
Great, thanks @luma! 👍
@fossil hearth posted a code wall, it is moved here --> https://paste.ubuntu.com/p/GDBT6Qk96c/
can somone please help me with the above link ? i think its very simple..
You have to make a for loop to iterate on the elements of values
aha... can you please show me how its done ? thanks ❤️
assuming your json is in the variable json_value:
{%for value in json_value["values"] if value[0] == "test 2" %}
{{value}}
{%endfor%}
and you can replace {{value}} with wathever ou want ({{value[i]}} i being between 0 and 3)
I want to create a templated sensor which combines the values of two entities. Is there a way to then hide those entities (without disabling them), so I don't accidentally pick them in an automation instead of the templated sensor?
nop
ok thanks, assumed not but worth asking 🙂
guys.. command line entities don't have attributes ?
attribute template i mean ...
Can I make a template to reset a scene to the way it was before.
I making a scene to that goes off when my van alarms goes off . lights flash etc .. So when i tell alexa reset van alarm all the lights and that go back to the state they was before ?
How would it know what scene to revert back to? I guess you'd need to record it in a variable each time the scene is changed
but yes it's possible... maybe not as easy as youd like tho 🙂
it's very simple. on the fly scenes but not template related
would this revert back?
you make a new scene before you do anything and then go to it when done
https://www.home-assistant.io/integrations/scene/#creating-scenes-on-the-fly not scenes and templates don't mix really
except for the creation of them, I guess
not restoration
how can i give attributes to command line sensor ? its for google sheets api
am using command line since there are above 255 characters, but i don't want to call the api every single time, i wane do attributes.. how to do in this case ?
thanks 🙂
what if my json looks like the below
@fossil hearth posted a code wall, it is moved here --> https://paste.ubuntu.com/p/ztT2BhyTSZ/
trying to get in to values? don't think you can drill down. will just need to pull the whole thing and parse it out with template sensors
the whole things is above 255 tho.. i tried that
like how to pull out the whole thing ( i initally wanted to do that) just hitting the 255 block
Discord isn't like IRC, you don't have to tag people on every response. Keep in mind that every time you tag somebody, they get a notification ping. That can very quickly become annoying and people may block you.
When using Discord's new Reply feature it defaults to pinging the person you reply to, click @ ON to @ OFF to stop this - on the right side of the compose bar.
not sure if you can bypass that
like only if command line had template attributes it could have worked..
coz i dont want to abuse the api.. just one pull
might be be better off writing a custom integration
like a py script ?
cant belive this is the only way tho 😦
all these tools ... theres gotta be a way haha
well, that is one of the tools
just need the whole thing and then ill te,mplate it 😛
why does it need to be command line?
rest api is not able to pick it up due to its own limitations
its a curl -x get command
gotcha. probably going to need a custom integration then
i see :/
thanks buddy ... just worried coz am no programmer
well figured it out
json_attributes: has no limits
was able to pull the whole thing out
ah ok
@flint crown posted a code wall, it is moved here --> https://paste.ubuntu.com/p/mFbBzwd5dg/
I want to use a template for input_number.set_value
See here my automation:
https://paste.ubuntu.com/p/P57hBsgCGX/
But I got these error:
voluptuous.error.MultipleInvalid: expected float for dictionary value @ data['value']
you're templating the result {{3.5 | float}}
just 3.5 should do it if input number accepts decimals
Hi! I sent a wall of code in the wrong channel. This was my original message https://paste.ubuntu.com/p/MptRCgCdZS/
Long story short: I'm trying to make an automation that will turn on a light with a specific set of brightness + color temp depending on the sun position.
I made it work like this: https://pastebin.com/tXiHchz0 but of course it looks awful.
I wanted something like https://pastebin.com/1U4etb7u or actually like https://pastebin.com/U0pyQNrG
I wonder actually if Blueprints (https://www.home-assistant.io/docs/blueprint/) would help you make that "cleaner"
entity_id: input_number.heizung_vorlaufzeit
value: '{% if states("sensor.temperature") | float > 16 %} 1.0 {% elif 8 < states("sensor.temperature") | float <= 16 %} 2.0 {% elif 2 < states("sensor.temperature") | float <= 8 %} 2.5 {% elif -5 < states("sensor.temperature") | float <= 2 %} 3.5 {% else %} 4.5 {% endif %}}'
I get here the same error. Can you help me ?
you have an extra } at the end
ok, thx
always run your stuff through the template editor
but same error with the }
i run this template in the template editor
{% if states("sensor.temperature") | float > 16 %}1.0 {% elif 8 < states("sensor.temperature") | float <= 16 %}2.0 {% elif 2 < states("sensor.temperature") | float <= 8 %} 2.5 {% elif -5 < states("sensor.temperature") | float <= 2 %}3.5 {% else %} 4.5 {% endif %}
and get 3.5
input_number.set_value says: expected float for dictionary value @ data['value']
It worked
Well, actually I'm playing with that but IDK which would be the best way to do it. For example, IDK if I should do an automation just for the white lights with the condition: state of the sun and one for the yellow lights. Actually that was working, but I started to wonder if that abstraction level was a bit too much
https://github.com/JorgeAnzola/home-assistant-config/tree/master/automations/lights/kitchen
https://github.com/JorgeAnzola/home-assistant-config/tree/master/blueprints/automation/lights
Eh, it's personal taste
Now I'm on a version that supports Blueprints I'm starting to investigate them. I don't know it's going to make it easier to write automations, but at least I can keep logic in only one place
Yeah, you're right. Now that I'm thinking about it, I think I rather to avoid the logic in the templates and keep stuff like:
I'm not sure 😂
Maybe it's my way to not learn how the data_template thing really works
See? I was already wrong hahaha
0.115 brought sanity in that it no longer required you to specifically say this service call/data block has templates
Would be nice if among with condition: and action: would be an else:
😨
HA moves fast - it's easy to miss new, awesome, features
Maybe the answers I was looking for it's not in the automations/blueprints
Yes, mate, jeezus
I think that's perfect, thanks!
I seem to be struggling with a template, it's supposed to turn OFF a list of automations when boolean is ON and the other way around, but it only turns them OFF, never ON. Any help is appreciated!
https://paste.ubuntu.com/p/yntCSHXgpg/
Haha, wow, figured it out, that just took me way too long.. 😆
https://paste.ubuntu.com/p/btWNGh5pDM/
can be shorten
service_template: >-
{{ "automation.turn_"+trigger.to_state.state }}
Thank you!!
Hello, can someone please tell me what I'm doing wrong on template switch?
curl --digest -u user:admin -X PUT -d 'some data here' http://xxx.xxx.xxx.xxx/ISAPI/System/Video/inputs/channels/1/privacyMask
*user:password
hello all, quick question. I am trying to get an alert from the minecraft server integration that alerts me when a specified user logs on.
I am basing my automation on the players_online state change and I want to check the attribute players_list. I am not sure how to address that one entity attribute in the value_template though.
why am I getting an error using this in my call service notify action?
message: > {{ states('sensor.blah_minecraft_server_players_online') }}
tried that as well as using double quotes around the {{}} stuff
what error?
tried something like this.
- platform: template
sensors:
02_days_to_cleaning_0:
value_template: "{{ states('input_number.02_days_to_cleaning')|int }}"
But i cant use '02_days_to_cleaning_0' gives an error.
pick a different name
it is all but impossible to copy the errors in the UI. let me look and see it if is in the logfile on the server. 🤦♂️
so im trying to create a pair of sensors from one API call using the REST sensor... the API returns this: {"error":null,"result":{"effective_hashrate":987654321,"reported_hashrate":123456789}}
however i think I'm having trouble with the template. the sensor config is here: https://paste.ubuntu.com/p/6ttFQyVtBr/ any ideas?
Hi everyone. I have three rooms controlled by one nest thermostat in the spare bedroom. The two occupied rooms' temperature varies drastically from the spare room during the day. Can someone point me toward a template that would poll the temp sensors in the two occupied rooms, average the temps, and control the thermostat? Is this even the right approach?
it's fixed now 😉
I can't believe someone thought the old one was a good idea.
also my first PR 😜🎉
isn't trigger.entity_id a thing?
couldda sworn i used it before
@amber thicket state_attr('sensor.mining_hashrates', 'effective_hashrate')
for the value_template?
use that for your calls for the attributes
https://paste.ubuntu.com/p/4n5jR25Y4P/ i feel like im missing something
I think you need to set json_attributes_path
With {{value_json.result}}
And in your value template you search for value_json[0].result.name which refers a field I don’t see in your json
hmm
hi....i want to use statistics and i have some challenge. i want to have template sensor only when attribute driving is true in device tracker
driving can be true/false
I'm looking for some help. I want to create a template sensor from a attribute that has an EPOCH time in it. I want a sensor that basically says "Dustbin emptied 39 minutes ago" and later turns into Dustbin emptied 1 day ago" etc etc
{{ ((as_timestamp(now()) - (state_attr('vacuum.rockrobo', 'last_bin_out') | int / 1000))) }}
so this will spit out the time difference in EPOCH
but how to I get this to say what I want?
Dustdin emptied {{ ((as_timestamp(now()) - (state_attr('vacuum.rockrobo', 'last_bin_out') | int / 1000))) | timestamp_custom("%M") }} minutes ago
this wil give me the minutes. So I guess now I have to wrap it in more templating to convert it into hours when its more than 59 minutes
no, nevermind that isn't correct %M will just go from 00 to 59
What might explain a template-based sensor not getting any logbook/history entries despite changing states and seeing those changes reflected in the UI / developer tools? The state values are either '0', '1' or '2' This is the value_template: "{{ states.sensor.chargepoint_list.attributes['station_list']['summaries'][0]['port_count']['available'] }}"
Found info that says if 'units of measurement' are specified, then the value is not going to be in logbook/history. Is there a better approach to this? Context: I'm getting info on EV charging station to see how many spots are available. I had 'spot(s)' as the unit of measurement. Any way to show that on the UI as the suffix that follows the actual number without using units of measurement?
still fighting with ```sensor:
- platform: rest
resource: https://<API>
name: mining_hashrates
json_attributes_path: '{{ value_json.result }}'
json_attributes:- effective_hashrate
- reported_hashrate```, its putting the entire json result from the api server as the sensor's state instead of parsing out its attributes, any suggestions?
with sample results of the api call looking like {"error":null,"result":{"effective_hashrate":153333332,"reported_hashrate":111211946}}
I mean this looks simple but I’m not a coder so my brain is melting over here
~~```yaml
- condition: template
value_template: '{{ ( as_timestamp(now()) - as_timestamp(state_attr("binary_sensor.hue_motion_sensor_1_motion", "last_changed")) |int(0) ) > 900 }}'```
How do I get the time the sensor last changed states? That doesn't work. I'm trying to use it as a conditional so that it doesn't turn the lights off on me unless motion hasn't been detected for a bit.~~
value_template: '{{ ( as_timestamp(now()) - as_timestamp(states.binary_sensor.hue_motion_sensor_1_motion.last_changed) |int(0) ) > 900 }}'``` This works. Not sure why I can't pull it with `state_attr`, but it doesn't seem that I can.
who can help me with a nested template of sorts? i currently have 3 ups and am using this to message myself which ups has lost power "message: "{{trigger.to_state.name}} has lost main power!"
but i want to include a state template to find the remaining time left of the ups that just lost power with
{{states('sensor.ups_main_ups_time_left') }}
but need to replace that entity with whichever one triggered it? make sense
states('trigger.to_state.name') or similiar?
but idk time left is another entity to the device main ups.
@royal vortex last_changed isn't an attribute 😉
@boreal fiber need to know where the data is coming from before we can make suggestions
mqtt is polling apcupsd. each ups is a device that has 2 entities im trying to work with. status online/commlost and time left
{% set map = {'trigger_entity_1': 'sensor.entity_1_time_remaining', 'trigger_entity_2': 'sensor.entity_2_time_remaining'} %}
{{ '{} has lost main power! {} minutes of charge remaining.'.format(trigger.to_state.name, states(map[trigger.entity_id])) }}
how can i have this list out the friendly names instead of the values under the same conditions.
{{states|selectattr('entity_id','in',state_attr('group.test_branches','entity_id')) | map(attribute='state') | reject('in', ['unavailable', 'unknown']) | map('int') | select('gt', -5 ) | list}}
i've tested this on some of my own:
{{states|selectattr('entity_id','in',state_attr('light.woonkamer','entity_id'))|rejectattr('state', 'in', ['off', 'unavailable']) | selectattr('attributes.brightness', 'gt' , 0)| map(attribute='name') |list}}
so don't do the map's until you want to map what's in you list.
{{states|selectattr('entity_id','in',state_attr('group.test_branches','entity_id')) | rejectattr('state', 'in', ['unavailable', 'unknown']) | selectattr('attributes.int', 'gt', -5) | map(attribute='name') |list}}
if I didn't make any mistakes 😉
hey ! 🙂 thanks for the help but i got this as an error UndefinedError: 'mappingproxy object' has no attribute 'int'
we need to run the value against the state
so the state is a value, unless it's unavailable or unknown?
yes that is correct!
{{states|selectattr('entity_id','in',state_attr('group.test_branches','entity_id')) | rejectattr('state', 'in', ['unavailable', 'unknown']) | selectattr('state', 'gt', -5) | map(attribute='name') |list}}
should be it then ( I hope ) 😉
it works ❤️ just needed to add '' around the -5
you are the man !
bless you dude
thanks
@uncut path posted a code wall, it is moved here --> https://paste.ubuntu.com/p/DkJ8qyFFVb/
You have to indent the entity_id: to be bellow data:
- service: 'input_boolean.turn_{{"on" if trigger.event.data["args"][0] == "activate" else "off"}}'
data:
entity_id: >
{% set option = trigger.event.data["args"][1] %}
{{expand(option)[0].entity_id}}
and replace data_template with data
Oh man I feel dumb, thanks a lot for you help. I copy the call of the service from the automatisation UI panel and the entity_id was outside data
action:
- service: input_boolean.turn_on
data: {}
entity_id: input_boolean.notify_lucas
this last one is correct, but if you use template in entity_id, it needs to be under data
Because you can.
They're interchangeable for now, but data_template will disappear eventually.
Haha yeah sure, I started all my telegram automation with data
Ok I picked the wrong one, thanks I will update everything
A while back, picking data_template made sense.
@lime grove #integrations-archived
Could someone help me, (I think) I'm having a templating problems. https://paste.ubuntu.com/p/Pc7fGQ4t4M/
What I want to achieve: sensor.total_consumption_shelly_plug should summarise the value of the 5 listed Shelly plug sensors total_consumption value into one.
Everything works like a charm, until I restart my HA. Then at the start, all of the Shelly sensors total_consumption value is unknown or empty or 0 something, therefore the value of my sensor.total_consumption_shelly_plug is also empty, which will then be updated in a matter of few seconds into the correct value, which leads into my utility meter to have wrong data.
Before restarting my HA my utility sensor had value of 8.81 and after the restart it was 15.93, because (this is only my assumption) the utility meter thought that I spiked ~8kWh consumption in couple of seconds.
So, does someone have an idea how should I resolve this issue? can I add conditions into the sensor , like that it would not update its value, unless all the 5 Shelly plug sensors contained a proper value?
i wonder if min_max would handle this better
hmh?
so I should remove the | float after each sensor? or completely from the pasted yaml?
ok, gonna give it a try
if you remove the float casting you're just going to combine all the strings
{{ "4" + "5" + "9" }} -> "459"
meh
{{
[
states('sensor.shelly_makuuhuone_total_consumption'),
states('sensor.shelly_norttinurkkaus_total_consumption'),
states('sensor.shelly_nuutin_huone_total_consumption'),
states('sensor.shelly_tv_taso_total_consumption'),
states('sensor.shelly_tv_taso_viihde_total_consumption')
]|map('float')|sum|round(2)
}}
little more compact
would have the same problem though