#templates-archived
1 messages Β· Page 29 of 1
You don't really have any control on what homekit does other than exposing or not exposing entities via HA
Ok so I found a workaround. Voice commands were getting confused by the five switches all with the same name. I was able to ungroup the switches in HomeKit, rename the redundant ones (they were Called Off, Medium, Low, High) and rename them all to 'Ignore Me' and remove them from the Home View. That leaves only the fan, which responds as expected, although it seems HomeKit has its own ideas for what low medium and high mean, but I can deal with that.
seems like alot of work when you could have just removed the presets on a fan that you only expose to homekit
@mighty ledge what does something like {% else: %} do? So the colon? I saw something in the docs about parsing all as a block, but didn't really understand what that meant
I've never seen that
I'm skeptical it exists
where did you see that?
apparently the documentation mentions {% %} as the 'code block', i.e. it's a line that executes code
but else: isn't something I would expect to see in jinja
oh
I found a mention of this
it does nothing
so it's only for readability if you're used to python
in python...
for i in range(4):
i
is the equivalent
yeah the word block refers to this {% the code here %}
but it's basically saying the normal python rules w/ colons can be used
optionally
I have an air purifier with 1 preset mode ("sleep"), and 3 speeds (33%, 66%, 100%)
Rather than needing to perform a special action to turn the fan to "sleep", I'd like the fan slider on my dashboard to set to these 4 options as if they were all percentages.
25% on slider = sleep preset 50% on slider = previously 33% 75% on slider = previouslly 66% 100% on slider = previously 100%
I've attempted to use a template fan (https://www.home-assistant.io/integrations/fan.template/), but I'm struggling to find the right combination of letters despite a handful of attempts
I'm hoping for some suggestions on how I could get this done π
Latest template attempt:
http://pastie.org/p/6VK1sgcAbtzSN0xnKGtCKA
Hello
I am looking to make a template to set the value in seconds in a timer helper from the value of an entity
Can anyone hint me in the right direction of a solution being it documentation, forum posts or any other form of guidance ?
@hazy charm
Do either of these look like they could help you?
"time" and "number" in HACS might be helpful searches
https://github.com/htmltiger/numberbox-card
https://github.com/GeorgeSG/lovelace-time-picker-card
@civic cargo
I was hoping to use
https://github.com/rianadon/timer-bar-card
and i need to set the value of a timer helper to the value of an entity to show a "progress bar" of the started progress which will have a variable time
@hazy charm
I see
I think you could use the number box card to set it, and and timer bar card to display it
I could be mistaken though
You have to use a choose in your set_percentage actions
i will definitively give it a try, did not know cards could be used for that
i.e. if the percentage is 25%, then choose to run an action that sets the sleep preset.
if the percentage is 50, set the percentage to 33, if the percentage is 75 set to 66, etc
you don't need preset modes at all for the template fan either
and your percentage_template needs to return 0, 25, 50, 75 or 100 based on the state of fan.air_purifier
i.e. if the preset mode is sleep, return 25, if it's off return 0, if it's on return 50 if it's 33, 75 if it's 66, and 100 if it's 100
testing, please hold
@mighty ledge
Understanding it the way I am, I feel like I need a script to do what your suggesting, but your description doesn't feel that way.
Am I misunderstanding?
That is to say, I think I understand the principal of what you're suggesting, but execution is still eluding me
I fail to see the wqay to use the numberbox card to set a timer helper value from another entity value, I might be a little to new to this
Oh no, I think I misunderstood your initial request.
I was offering a way to manually set the timer, rather than receive that from another entity.
Perhaps you can make an automation that sets the state of the helper == the state of the entity
I'd start in the template editor
That is propably the way, but i do not have the necessary knowledge to do that on my own unfortunately
I'm sure it doesn't fully resolve your issue, but a template sensor feels like the way.
Let this guide you
https://community.home-assistant.io/t/update-helper-based-on-state-of-another-helper/409889
This looks to be a conditional static value, i am looking to set the time to the value of a dynamic entity.
To explain i am trying to make a conditional card appear with a timerbar when a switch is turned on which has a set inching value in seconds.
I am using this switch to control my microwave oven which has a stuck timer knob
The set_percentage field is basically a script field.
So you can write a script and call it or write the full script in that field
how do i get the enitity the name of the highest valued entity ?
{% set mylist = states("counter.csgo_thomas_deagle")|int,
states("counter.csgo_mikkel_deagle")|int,
states("counter.csgo_oliver_deagle")|int,
states("counter.csgo_holst_deagle")|int,
states("counter.csgo_max_deagle")|int %}
{{mylist|max }}
Wth a namespace and for loop, as states are strings and you can't properly sort them in a one line template
hi TheFes,
The fish tank just fed the fishes but I still got unknown at unknown notification.
https://imgur.com/xM3i5zr
automation template
http://pastie.org/p/6JO0joKVn2Uk0S6ljjoW7O
logs showing an error
Logger: homeassistant.helpers.template_entity
Source: helpers/template_entity.py:329
First occurred: 10:29:57 PM (1 occurrences)
Last logged: 10:29:57 PM
TemplateError('ValueError: Template error: timestamp_local got invalid input '2023-02-13 20:29:57+00:00' when rendering template '{%- if state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1') -%} {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %} {{ as_datetime(feed_record.timestamp)|timestamp_local }} {%- endif -%}' but no default was specified') while processing template 'Template("{%- if state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1') -%} {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %} {{ as_datetime(feed_record.timestamp)|timestamp_local }} {%- endif -%}")' for attribute 'timestamp' in entity 'binary_sensor.feed_record_result'
{% if trigger.platform == 'state' or states('device_tracker.delonghi_primadonna') == 'not_home' %} how would I make this to only trigger if not_home is for 5 minutes or greater?
@sonic sand that error is not related to the automation
It looks like the old code for the template sensor
for the unknown thing a trace (you can download the json) will help
weird, how can It still use the old code if I already changed it and restarted the whole HA.
From where can I get that json file?
in settings > automations > select your automation > traces (top right)
then make sure to select a trace which has the wrong message
and then you can download the json file with the button in the top right
Problem that it's already gone, there were 5 more traces after the one with the unknown issue
https://imgur.com/yolGlhd
okay, it triggers quite often..
Is there a way to get the 6th trace?
nope
yeah.. my internet is bad here
haha! it just sometimes goes offline for a few seconds and then comes back 2 mins later - I think its a BT issue
ok if that will happen next time i will get the json.
maybe you can help me with the last sort of "log" error
In the watchman report, I get this error
group.temp | unknown | templates.yaml:38
templates.yaml:
http://pastie.org/p/5eWUT7o5fFIi1oIBAybpCo
groups.yaml:
http://pastie.org/p/3H0KaeJWt3HVMpyPj6OtPs
It does show me 5/5 on the frontend side but why does it say unknown? all those sensors are working properly.
this should resolve the unknown messages http://pastie.org/p/5ngdmq6ZS58QjL6UCrtmTO
wait but you said it's not related to the automation
yes, but you were still receiving notifications with unkown. This should solve that
but the error you posted was not related to you receiving messages with unknown
I don't understand the use of that template sensor with the group, it will always show you X/X
perfect
well I wanted to show the total amount of tempature sensors and how many of them are showing something and not on OFF state or Unknown.
but that is not what that template does
I know, I couldn't find a way to do it so I used that...
the parts before the / and after will always be the same number
yeah
not sure why Watchman complains about it though
very annoying to see that
If you start using more complicating templates using partial matches of entities, you will get more Watchman logs
As an expert does your System -> Logs are empty all the time? or it pops sometimes an error or two
so, I am trying to make a template binary sensor with attributes of the time we left and entered a zone.
- trigger:
- platform: state
entity_id: person.jurgen
binary_sensor:- name: "Jurgen at School"
state: "{{ is_state('person.jurgen', 'School') }}"
attributes:
arrived: >-
{% if (trigger.to_state.state == "School") or (trigger.to_state.state == "school") %}
{{ now() }}
{% endif %}
left: >-
{% if (trigger.from_state.state == "School") or (trigger.from_state.state == "school") %}
{{ now() }}
{% endif %}
Now, the attributes do not work. They are empty, do the trigger states like in an automation work like this? https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-numbers-selects-and-sensors This doco implied to me that it would, but why do I get empty attributes? The binary_sensor state works.
use a zone trigger
keep in mind that if you use an ifstament like that, when the statement fails, it will be empty
so you need to fall back on the previous timestamp
using this.attributes.arrived when that happens
but you also need to make sure that all of that exists
becuase it won't at start up
basically, what you're trying to do isn't going to be simple if you aren't a templater
yeah, I hear you. Thanks
https://imgur.com/MOnk5Ge
I got spammed tonight after changing the template you sent me, what could it be now?
Logs warning:
http://pastie.org/p/5dLAjdeXNfZALXcUoxnQFs
Automation template:
http://pastie.org/p/0lFMQzcPkYJYSXUjgaZumE
can this be written to turn on if the state of the sound sensor has been above 150db for more than 30secs instead of the way it is currently?
- platform: state
entity_id: sensor.samsung_j3_ipcam_sound
binary_sensor:
- name: "Bathroom sound"
state: >
{{ (now() - states.sensor.samsung_j3_ipcam_sound.last_changed).seconds < 5 }}```
Assuming that it started below that, just use a numeric_state trigger
- trigger:
- platform: numeric_state
entity_id: sensor.samsung_j3_ipcam_sound
above: 150
binary_sensor:
- name: "Bathroom sound"
state: >
{{ (now() - states.sensor.samsung_j3_ipcam_sound.last_changed).seconds < 30 }}```
is this it?
Just use for:
- platform: numeric_state
entity_id: sensor.samsung_j3_ipcam_sound
above: 150
for: "00:00:30"
binary_sensor:
- name: "Bathroom sound"
state: >
{{ (now() - states.sensor.samsung_j3_ipcam_sound.last_changed).seconds < 30 }}```
like this?
state template REQUIRED
is good now?
No
π¦
What does that template evaluate to?
turns the sensor on if the sound sensor changed states in the last 30s
You already did that with the for:
that's why I said to take out the template
Which is not allowed
Add a trigger for below 150 and use {{ trigger.to_state.state|float > 150 }} as the state
but wouldn't that trigger it when it goes below that threshold?
yeah
Then
Don't use a trigger at all, use a state template of {{ states('sensor.whatever')|float > 150 }}, and use delay_on: '00:00:30'
There are many ways to do it, but I think that's the easiest
Forgot to change the message template
- service: notify.home_assistant_group
data:
message: |
{% if values.error %}
π β The fishes have not been fed at {{ values.timestamp }} β
{% else %}
π The fishes have been fed {{ values.value }} portions at {{ values.timestamp }}.
{% endif %}
and I shouldn't have removed the original condition, this should resolve both issues http://pastie.org/p/6b8TD8KxB94qqOKdfXBvv1
Thanks dude, will check that out
{{ now() >= alarm - timedelta(minutes=1) if alarm else false }}
This is the shorthand of what?
What does if alarm mean?
if exists? if true?
if is is anything besides falsely
So not none, false, "", 0, [], {} and others I missed
doesnt the doc on state of a binary https://www.home-assistant.io/integrations/template/#binary_sensor apply to the binary rest sensor?
using a template like value_template: > {{'Groen' in value_json.rss.channel.item[12].description}} returns True, when used in a regular rest sensor, but 'off' in a binary rest sensor...
template is True, so should be 'on' for the binary rest ....?
- platform: rest
unique_id: platform_rest_knmi_waarschuwingen_binary
resource: https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml
name: Platform rest knmi waarschuwingen
value_template: >
{{'Groen' in value_json.rss.channel.item[12].description}}
sensor:
- platform: rest
unique_id: platform_rest_knmi_waarschuwingen
resource: https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml
name: Platform rest knmi waarschuwingen
value_template: >
{{'Groen' in value_json.rss.channel.item[12].description}}
You are not creating a binary_sensor wiht the bottom one, you are creating a sensor
and a sensor will not convert true to on
So it actually does this.. I don't understand your question
oh wait
now I see it
the binary sensor should have converted the True of the template to 'on'
True vs off
yes, that π
That is indeed very strange
BTW I would turn it around, make the sensor on when Groen is not in de description, but that's not the question here
using a regular binary:```
-
binary_sensor:
- name: KNMI waarschuwing Noord-Brabant
unique_id: knmi_waarschuwing_nb_binary
state: >
{{'Code Groen' in state_attr('sensor.knmi_waarschuwingen_nb','description')}}
- name: KNMI waarschuwing Noord-Brabant
correctly
sure, wil do later on, but for now I was experimenting, because I could not get this out of the restful sensor, https://community.home-assistant.io/t/knmi-rest-sensor-configuration-and-preselect-individual-items-in-a-huge-attribute/533610/2 and first tried to get the platform rest to behave as expected
What if you do something like this?
{{ 1 if 'Groen' in value_json.rss.channel.item[12].description else 0 }}
just to test if that works
if it does, it looks like a bug in the restful binary sensor to me
still 'off'.... done: https://github.com/home-assistant/core/issues/88068
will file an issue
I have a simple dht22 sensor, that I'm trying to get into HA, but I'm overseeing something...
{"humidity":26.4,"temperature":21.3}```
and:
```mqtt:
sensor:
- name: "DHT22 Temperature"
state_topic: "neo2/dht22"
unit_of_measurement: "Β°C"
value_template: "{{ value_json.temperature }}"```
and yet still:
`ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'value_json' is undefined when rendering '{{ value_json.temperature }}'`
What am I missing??
I don't think that's a bug
I think you screwed something up with your unique_id
and you're looking at the wrong entity
your unique_id is platform_rest_knmi_waarschuwingen_binary yet the entity you're creating is binary_sensor.platform_rest_knmi_waarschuwingen and that does not jive with the autogenerated entity_id's
Although I do see the name there
yeah, I did edit those manually, because there are a few related restful sensors around. to be sure, I deleted those, restarted and recreated them
well, I don't see how this can be a bug
because the test cases test this situation
and the code checks for 'true', 'on', 'open', and 'yes'
but it first attempts to assign it as a bool
yes, that is what was confusing me. given the fact my unique_id is in fact unique, there cant be any system confusion cant there?
so the rest data you're using is XML, are you sure you aren't running into using an incorrect key issue?
If the result of the sensor with the same template is True, the binary sensor should be on and not off
That's why I thought it might be a bug somewhere
Looking at the code, I don't see how it can be
The only possibility that I see for an error is if the rest backend does not have data
def _update_from_rest_data(self) -> None:
"""Update state from the rest data."""
if self.rest.data is None:
self._attr_is_on = False
return
response = self.rest.data
if self._value_template is not None:
response = self._value_template.async_render_with_possible_json_value(
self.rest.data, False
)
try:
self._attr_is_on = bool(int(response))
except ValueError:
self._attr_is_on = {
"true": True,
"on": True,
"open": True,
"yes": True,
}.get(response.lower(), False)
if there's no rest data, it will return false always
otherwise if there is rest data, it attempts to make the response a boolean. If that fails, it takes the lowered string result and see's if it's `true', 'on', 'open', 'yes'.
if it is, it returns true, else false
pretty simple logic
so the only screwup that can happen is self.rest.data not being populated.
ah yes, it uses lower
I thought it might be that the result was "True" like in the (non binary) sensor, but that is coverted to lowercase
so that also can't be the issue
I kinda understand this code π
It converts things like true, false, "1" to an integer, and then to a boolean value, if that results in true it turns the binary_sensor on, if it results in an error, it checks for the strings in the dict if it can match one of those (in lowercase) and otherwise returns false
it's python which is almost identical to jinja
I'm 90% sure you could contribute to core
there are some principles you'd need to learn but it wouldn't be too hard
still looking where to start to learn those principles, but currently I'm already contributing to the intents repo π
you already understand object orientation, the next thing you'd need to learn is object scope when coding
are you using alexa for intents?
no, for the new Assist integration
well, the rebranded conversation integration π
ah
But I will find some time to learn python (at least for HA) somewhere in the future
It looks like it's cause the regular sensor has conversion from XML to JSON in its update; however, the binary sensor does not. When the binary sensor renders the template, it fails since value_json isn't set.
https://github.com/home-assistant/core/blob/dev/homeassistant/components/rest/sensor.py#L127
yeah, that's entirely possible. This would also mean this bug has existed forever
Also, there are no test cases that verify XML works
Then again, the binary sensor makes no mentions that it will work with XML where the rest sensor does
Okay, so not a bug, but a missing feature compared to the rest sensor π
That it appears to be
However that would be a bug for the rest integration
however that doesn't mention XML either
well, actually, the rest integration handles that
and it does work with xml
nope, I'm wrong, that should also fail
Seems like the rest update coordinator should handle the xml to json instead of it being handled in the sensor
then it would fix binary sensors
without making changes to binary sensors]
in any case.... we have an issue π btw, commenting the complete platform: rest sensor does Not take out the entity...
that doesn't mean it will be fixed if xml wasn't intended to be used w/ xml
just keep that in mind
taht falls in line w/ feature requests
its remains in the states overview, until I restart
not sure what you mean by that
sensor:
# - platform: rest
# unique_id: platform_rest_knmi_waarschuwingen
# resource: https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml
# name: Platform rest knmi waarschuwingen
# value_template: >
# {{value_json.rss.channel.item[12].description}}
still shows:
but I can not delete it
restart
thats what I said.... only on restart
yes, when you reload, HA doesn't know that the entity no longer exists
also without unique_id. If one does not use unique_id, it constantly adds new entities..... _2, _3, _4 etc
that's a caveat of using YAML reloads & unique_id
it's like this for all YAML reloading & the use of unique_id
unique_id registers the entity in the entity registry, so now the system see's it. The system does not know it comes from yaml
on template: we can simply delete the entity
so when you reload, the system is happy
but it doesn't k now that the yaml has been removed
until you restart
template is the same way when you use unique_id
now that I have your eyes: we can use value_template: > {{value_json.rss.channel.item[12].description}} in the value_template on the platform: rest, but we can Not do that using the rest: config
what could be the reason for that?
no, for regular. see eg:```
-
resource: https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml
scan_interval: 900sensor:
- unique_id: knmi_waarschuwingen_basis
name: KNMI waarschuwingen basis
value_template: >
{{now()}}
json_attributes_path: "$.rss.channel.item[0]"
json_attributes:- title
- category
- description
- enclosure
- link
- guid
- pubDate
- author```
- unique_id: knmi_waarschuwingen_basis
if I replace the value_template with eg value_json.rss.channel.item[0].description it returns unknown
So you're putting that in the sensor: field for the rest integration?
thanks
you can turn on debugging for the rest integration to see where it's going wrong
the sensor platform has a ton of debugging
lines
there simply is no syntax for that template I can find to give something useful...
are you following the rules for XML when getting information out?
uhm..... dont know...
IIRC (I don't have them memorized) You need to selectively use $ with attributes
xml is dumb
so it forces us to do different things to convert the values to json
given the fct the platform: rest can do so without anything further, I was perplexed by the output in the rest: config
because you can have an XML attribute and an XML name at the same level with the same name, but you need to distinguish between them
Hello, I hope I am right in this Channel :). Currently I am controlling my remote control of my my shutters with a servo and the EspHome integration so ItΒ΄s possible to set the Servo to a specific level so that It press a button on my remote control. Now my question is how can I create a cover template in HomeAssistant to get a better control over the ui.
so, currently, on binary sensors in the Rest integrations, I am stuck with a platform: rest binary config that can not evaluate the value_template correctly, and a rest: binary config that wont allow the same path to the item in the attribute.... for now, a template: binary_sensor to the rescue. Whether or not these issues would qualify as feature request should not be returned to the user. The inconsistency in behavior is remarkable. And that is always bad.
btw, value_template: > {{True}} or {true}} do make the binary state to 'on' π
there simply seems to be no correct connection between the resource and the referencing value_template: value_template: > {% set code = value_json.rss.channel.item[12].description %} {{'Groen' in code}}
as is logged:```
Logger: homeassistant.helpers.template
Source: helpers/template.py:624
First occurred: 14:34:14 (14 occurrences)
Last logged: 14:42:29
Template variable error: 'value_json' is undefined when rendering '{{'Groen' not in value_json.rss.channel.item[12].description}}'
Template variable error: 'value_json' is undefined when rendering '{{'Groen' in value_json.rss.channel.item[12].description}}'
Template variable error: 'value_json' is undefined when rendering '{% set code = value_json.rss.channel.item[12].description %} {{'Groen' in code}}'
@terse pike I converted your message into a file since it's above 15 lines :+1:
I still don't think you understand what the problem is
You cannot use XML w/ binary_sensor rest
It simply does not work and it will not populate json, so value_json will be undefined
You keep focusing on the template, the template is fine
it's your resource
your resource outputs xml
rest sensors can read from XML, rest binary_sensors cannot read from XML
You can, but you can also just create the cover in your esphome
@terse pike you can't put switches in the template integration. Switch is only available using the legacy template integration. Also, they key for sensor: is not sensors:. Notice the lack of the letter s.
thanks, so can you help me understand how to implement this: https://community.home-assistant.io/.../simple-way.../394058
there is advice there how to use the ultrasound sensor of the echo dot 4 within the HA platform
that's not a working link
you can create a template switch, you just have to use the correct placement in your configuration.yaml
it needs to go in the switches section and the documentation covers the yaml format.
So what's the problem?
those directions seem straight forward
yes, I am aware. And I added that inconsistency to the issue tracker.
the template switch goes in configuration.yaml in your switch: section, and the sensor goes in configuration.yaml in your sensor: section
so i should not use my template yaml?
Do you undertand what you did wrong
you put
template:
... stuff
and that's not correct
you need to put the switch in the switch section.
switch:
... stuff for switch
sensor:
... stuff for sensor
and make sure your code matches the code in the post. You changed things and removed the -platform: template line for both of your entities
you also have a . in the name of your switch and sensor
please follow the examples in that post and the examples in the documentation
yaml is very sensitive to spaces, and naming, and punctuation
all have to match
@terse pike I converted your message into a file since it's above 15 lines :+1:
but this is the name of my echo
ok? yaml does not allow the period in the name
if i define a variable to pass into a script, do i have to redefine the same variable again inside that script to get it to pass on to another script inside the script?
yes
if you have a script that passes X, then any service that's called where you want to pass X, you have to declare X in that service call data
(https://ibb.co/syqWYb8) Here is an action that has to be performed. This action contains (https://ibb.co/ZgyxdL3) Where time is triggered, action is performed. The action send the data to a script connected to a skill and sends it to echo device. Then you can say yes or no(https://ibb.co/Lh7Z1wD) to the action (ex. if tv is idle for more than 5 mins, switch off. If said yes ). This will send data to yes automation(https://ibb.co/ZL44FbY). Now what I want is the yes enitity to be automatically updated to the action playing so I dont have to create multiple Yes for every action I input. The code can be found here (http://pastie.org/p/2PuGtMTCPor9O3z5EwKCWv) for all this.
any docs for that? π
??
how are you passing the variable to your current script...
can it be a 'simple' if variable X = A, then set variable Y = A?
im not at home with this stuff yet
lemme check
if you pass
service: script.something
data:
a: 1
then anything inside that where you want a to continue...
service: script.somethingelse
data:
a: "{{ a }}"
data:
override: 1```
thats helpful
thanks allot
i have some light scripts inside a wrapper script. But sometimes i want a certain light to do something else then default
then in the script of the light itself i make a choose, with the variable as condition
ill go and toy with this info. thx
@terse pike indentation is also off, there is only 1 space before media_player.avidad_echo_dot_motion:
eh, that will still work
as long as everything else is indented at that level too
e.g.
this:
is:
valid:
yaml:
foo:
oh okay, I thought it always had to be in pairs of two spaces π
nope
yaml crazy
dictionary keys and listed items need to be the same level
that's pretty much the only spacing restrictions
so it's impossible to single space a listed item too btw
cause -foo: is not valid
looking for some assistance. I'm trying to write an automation that gets triggered by a state change of all lights in an area. As I understand it, templating can help me here but I'm having trouble finding a yaml example of this use case.
description: ""
mode: single
trigger:
- platform: state
entity_id: <Id of your event>
condition: []
action: []
you can create an entity to specify it a an area
and add that in entity_id
Sorry, I'm not making the connection. I have an Area defined (lets call it "Outdoors"). In it, I have several entities. I want to trigger when any on of those entities "Outside" have a state change. I know I can list all the entities in the entity_id section of the state trigger, but what I'm looking to do is have the entities dynamic and populated by the area so any new entity added the "Outside" area get captured by the automation
This might help you: https://community.home-assistant.io/t/templating-filter-list-of-entities-by-area/365523
I think you could use a template trigger, not a state trigger, and write a template to filter down if any lights in area are on or off.
Thanks TimO. I actually found that resource but I'm having trouble understanding it in the context of the overall automation yaml.
review this also: https://www.home-assistant.io/docs/automation/trigger/#template-trigger
You have template trigger which fires when a template becomes true, and you have a template example that can tell you if lights in an area are on or off. I think you should be able to put it together from those two things (or ask more questions if still confused on a point).
I think so, but I don't care if the lights are on or off so much as if the state of one of the entities change. I'll see if I can piece it together from the links
What you're looking for isn't really possible without extensive setup
if you are trying to trigger off a single entitys state change inside a group or area, you're going to have to jump through hoops or declare all the entities out in the automation.
Really? That seems like such a simple concept.
Hi, i was setting up actionable notification for my echo device, did everything now want to create this:
(https://ibb.co/syqWYb8) Here is an action that has to be performed.
This action contains (https://ibb.co/ZgyxdL3) where time is triggered, action is performed.
The action send the data to a script connected to a skill and sends it to echo device.
Then you can say yes or no(https://ibb.co/Lh7Z1wD) to the action (ex. if tv is idle for more than 5 mins, switch off. If said yes ).
This will send data to yes automation(https://ibb.co/ZL44FbY).
Now what I want is the yes enitity to be automatically updated to the action playing so I dont have to create multiple Yes for every action I input. The code can be found here (http://pastie.org/p/2PuGtMTCPor9O3z5EwKCWv) for all this.
noob question: any reason why a template would return true in the dev tools but false in the automation condition? π
{{as_datetime(states('sensor.levisamsung_next_alarm')).astimezone()}}
{{(as_datetime(states('sensor.levisamsung_next_alarm')).astimezone() < now() or as_datetime(states('sensor.levisamsung_next_alarm')).date() > now().date())}}
returns
2023-02-15 08:00:00+01:00
True
in the dev console, but in the automation i get false in the trace
the template:
- if:
- condition: template
value_template: >-
(as_datetime(states('sensor.levisamsung_next_alarm')).astimezone() <
now() or as_datetime(states('sensor.levisamsung_next_alarm')).date() >
now().date())
then:
(...)
(so just a copy pasta)
trace:
Executed: 14 February 2023 at 18:34:14
if
Executed: 14 February 2023 at 18:34:14
Result:
result: false
if/condition/0
Executed: 14 February 2023 at 18:34:14
Result:
result: false
entities: []
this is probs something stupid as its my first template, but i can't find it
now this seems out of the ordinary... a direct template on a rest resource:{{ states('sensor.platform_rest_knmi_waarschuwingen_pubdate')}} returns Tue, 14 Feb 2023 19:58:00 +0100 . trying to get that into a device_class: timestamp . Any guidance how I should proceed here please?
is the only way to build a strptime? like {{ strptime(states('sensor.platform_rest_knmi_waarschuwingen_pubdate'), '%a, %d %b %Y %X %z ')}}
yes
seems odd hat you have a space at the end of your format though
Yes, Iβll fix that . And a default ..
this seems to be ok already:{{as_timestamp(strptime(states('sensor.platform_rest_knmi_waarschuwingen_pubdate'),'%a, %d %b %Y %X %z'))}}
or, directly in the rest sensor value_template π ```
- name: Platform rest knmi waarschuwingen pubDate
value_template: >-
{{as_timestamp(strptime( (value_json.rss.channel.item
| selectattr('title', 'eq', 'Waarschuwingen Noord-Brabant')
| first)['pubDate'],'%a, %d %b %Y %X %z')) }}
setting device_class: timestamp to that breaks the sensor though and makes it return unknown
device_class: timestamp expects a datetime, or a isoformat datetime string
not a timestamp
which is somewhat confusing, but if you remove the as_timestamp it should work
right, so I should set the class to the strptime template directly?
bingo!
thx
on a default value there, most templates I found simply use ,0 which seems an odd default really . wouldnt something like now() be more useful?
- name: Platform rest knmi waarschuwingen pubDate
value_template: >-
{{strptime( (value_json.rss.channel.item
| selectattr('title', 'eq', 'Waarschuwingen Noord-Brabant')
| first)['pubDate'],'%a, %d %b %Y %X %z', now() ) }}``` ?
that's why you don't copy examples online and you build the code yourself
I use whatever default I want to use that makes sense for the context of the sensor
is it possible to read a json file and render it with a template?
i guess i should ask what i'm after... i am using custom:auto-entities to "pre-populate" cards based on json in a template sensor attribute, and this works, but is rather cumbersome.
i'm wondering about defining these in separate json files just to clean things up some π€
I have a template trigger that should check if a esp sensor is in fact updating every 30 seconds (for testing purposes at the moment) but for some reason my trigger isnt fired when the 30 seconds mark has passed. instead it fires when the state changes. could someone tell me what im doing wrong?
- platform: template
value_template: >
{% if as_timestamp(now())|int - as_timestamp(states.sensor.zolder_temp_sensor_bmp280.last_changed)|int > 30 %}
true
{% else %}
false
{% endif %}
when testing the template in the dev tools it does work but i have to manually refresh it to update the outcome or wait until a state change happens for it to change from false to true. is there something wrong with the refresh rate of these template triggers?
its almost like these template triggers are only evaluated after an amount of time or on a state change. not actually calculating the timestamp in realtime. At the moment im using a seperate sensor with this template and the sensor turns on and off. and this seems to work fine. but with over 4000 entities i would like to reduce the amount of sensors as much as possible and was looking for a way to directly do this in an automation without a seperate sensor. Now i wonder if its even possible to do it the way i want right now
@full nacelle I converted your message into a file since it's above 15 lines :+1:
and it converts my msg into code. wow
I was trying to use chatgpt to answer my question but It seems I have exceeded the number of tries in an hour
The code he has made is this http://pastie.org/p/5hNqTWNdRIjYkCY2eMgVM3
What I want is to get a sensor which update my https://ibb.co/QKC8f8j entity_id in the arrow. I have multiple automation like these so they contain a common name action in them. Can anyone tell what's wrong in the code. THIS CODE WAS FOR THE TEMPELATE IN DEVELOPER TOOLS.
The error is when I check the entity in states. It remains blank throughout, when call the automation. the sensor code can be found here http://pastie.org/p/2kbIW2yruCgQIEAwqdJAEA
Some remarks
- you don't need this if else construction, as the part you are testing will return true or false itself
- you don't need to convert to timestamps, you can use the datetimes directly
now()will only be evaluated once per minute, so this will evaluate to true anywhere between 30 and 90 seconds after the state change
- platform: template
value_template: >
{{ now() - states.sensor.zolder_temp_sensor_bmp280.last_changed > timedelta(seconds=30) }}
Ok thanks so eventually it will work when I set it to 10 minutes for example. The only thing is that it won't be as precise right?
That explains allot about the random changing from true to false. It's not random but once per minute
Yep, now() is updated on the minute change
Any ideas on this?
Do you do something like value.value.value
<tr align="left"><th>Item</th><th>Stat</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
{%- if value is defined %}
<tr><td>{{ name }}</td><td>{{ value }}</td></tr>
{%- endif %}
{%- endfor %}
</table>```
Right now this looks like this https://imgur.com/a/QpQm2N2
Trying for this https://imgur.io/a/rUjyF8g
Sorry so you would just use name and value again in that next for loop?
I would use different variable names, to avoid confusion
What would it look like when I used name and value there I could technically put anyname1 anyvalue1 anyname2 anyvalue2 and it would just automatically understand that?
You probably don't really understand what you are doing π
Assume you have a directory like this
example:
key1:
subkey1: value1
key2
subkey2: value2
with example.items() you turn this into a list of tuples [( "key1", { "subkey1": "value1" }), ( "key2", { "subkey2": "value2" })]
With {% for name, value in example.items() %} you assign name to the first item of each tuple, and value to the 2nd item.
But you could also do {% for banana, apple in example.items() %}. It doesn't matter how you call these variables.
hi again
well the portions does show up (values.value) but there is a problem with the timestamp it showing unknown in the notification still.
https://imgur.com/10Lom9M
automation:
http://pastie.org/p/6iTChEY8DXolq0APPrGZbo
also someone at #automations-archived told me to create an automation for notification if the fishes have not been fed for more than 2 days and 6 hours I will have to create a template automation and I should consult in #templates-archived how to do it correctly.
Thanks man
There was a line missing in which the timestamp should be defined
This should resolve it http://pastie.org/p/4kimGus36fknbTkpQ0oOx3
I don't have time to look into the automation now
Sweet, thanks dude
You are correct in your assumption. I wasnβt aware of what I was doing. Thanks for the explanation. How do I use this tuple technique. I tried to add key, name, value and it said it only has two data points to work with.
Yes, there are only two
Instead of {{ value }} you need to use a new for loop which formats the value part
Can someone help me with my temp too?
This code is nonsense, as for all code generated by ChatGPT
There was no one to help so I choose the way
<tr align="left"><th>Item</th><th>Stat</th></tr>
{%- for [( "key", { "subkey": "value" })] in state_attr('sensor.printer_3d_system_info','system_info').items() %}
{%- if value is defined %}
<tr><td>{{ [( "key", { "subkey" })] }}</td><td>{{ [( "key", { "subkey": "value" })] }}</td></tr>
{%- endif %}
{%- endfor %}
</table>```
No, no, no... I was giving an example there, not a solution
But I don't have any more time now
(http://pastie.org/p/0NR6UVF0dDxpDV3rdFIAlD) Here is a script that I am using to call multiple automations. One of my automations are something like this. (http://pastie.org/p/76nQeMq0TGgDzDElqHrvXs). These automations have 1 word in common which is 'action'. What it does is it sends the data to alexa skill and then it receives it through this automation(http://pastie.org/p/24unVsQi8JuZtXFFvpxZLk) if said yes and (http://pastie.org/p/4NdEk4izPlKc5m9ZFhGQ5D) if received no from echo device. I dont want to create multiple yes received for every action automation.
not from ChatGpt
that this is a real waste
Your automations don't have a trigger, that makes no sense
For this one http://pastie.org/p/24unVsQi8JuZtXFFvpxZLk leave out the event_id in the trigger, and use `"{{ trigger.event.data.event_id }}" in the action
doesn't work
Look at the trace of the automation, does it actually trigger? Are you triggering it manually by using Run actions?
doesn't work doesn't help in resolving the issue
How do I format your example properly into the template?
Ok so when I use the my normal automation and trigger individually the action automation. It works perfect the code I use is this http://pastie.org/p/1vvLqwOAhiy1Re8nWrIdGU
Now I have multiple action automation and want the yes automation to only be one.
Something like this. I'm in mobile, so no guarantees
<tr align="left"><th>Item</th><th>Stat</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
{%- if value is defined %}
<tr><td>{{ name }}</td><td>
{% for k, v in value.items %}
{{ k }}: {{v }}</ br>
{% endfor %}
</td></tr>
{%- endif %}
{%- endfor %}
</table>
Why does this first automation doesn't have a trigger. Just use a script then
I will use it in alexa app routine
And this one id just a demo
For the test i am triggering it manually
I will be using this to confirm my things for exam if I turn off a computer and my files are not saved it will ask me if I am sure that I want to turn off my computer if I say yes it will turn off if I say no it will not I have such automattions all over my home so it is useful the sentences also can be changed but the response yes and no matters
#yes automation
alias: Received Yes
trigger:
- platform: event
event_type: alexa_actionable_notification
event_data:
event_response: ResponseYes
action:
- service: button.press
target:
entity_id: "{{ trigger.event.data.event_id }}"
mode: single
This should work as well
If not, answer I need to know if it does trigger, and if so, what the trigger variable looks like in the automation trace
Hi there, I'm having some trouble with a sensor template that grabs the second element value from a timer list that doesn't always exist. My original code is http://pastie.org/p/4BIQERkBelJzahahd6G8oa
Which produces errors in the log like:
Template variable error: list object has no element 1 when rendering '{{ states.sensor.living_room_display_timers.attributes.timers[1].local_time_iso }}'
Template variable error: list object has no element 1 when rendering '{{ states.sensor.living_room_display_timers.attributes.timers[1].label }}'
Template variable error: list object has no element 1 when rendering '{{ states.sensor.living_room_display_timers.attributes.timers[1].duration }}'
I've attempted a few different if statements to check if the element exists, but so far the error keeps popping up in the log. My last attempt was: http://pastie.org/p/7KRyeasznAaf9XDiBnysAa
I have some template sensors that can get really long states and want to cut them of a max chars and I've tried truncate but it does not seem to take spaces in to account. Is there anyway around that?
I've done this in the past but can't remember how it's done
TypeError: 'builtin_function_or_method' object is not iterable
still havent been able to get it to work :c
can someone help plz π₯Ί
I noticed that items() didnβt have some brackets on the end so I tried to add them but then got UndefinedError: 'str object' has no attribute 'items'
Try this then
<tr align="left"><th>Item</th><th>Stat</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
{%- if value is defined %}
<tr><td>{{ name }}</td><td>
{% for k, v in (value | from_json).items() %}
{{ k }}: {{v }}</ br>
{% endfor %}
</td></tr>
{%- endif %}
{%- endfor %}
</table>
Value will always be defined if system_info is a dict
Should check that attr for mapping before iterating
Dictionary items() always returns a list of tuples that has a key and value. Itβs impossible for it to be missing key or value. At worse it returns an empty list, which the for loop will skip
Both of those pastes don't exist anymore
you're right, but that part was working, I only concerned myself about the 2nd for loop for value π
I'm trying to get him to post his dump again
Last I remember, some of the main dictionary items had different values
yes, I think there was a system thing which was different
long story short, he may need to check to see if the attribute is mapping before trying to iterate instead of forcing a from_json because it should already be json
ah okay
yeah, but he needs to post the data again for confirmation
his data structure is definitely built for someone to create objects. It's not nice for jinja itering
JSONDecodeError: Input must be bytes, bytearray, memoryview, or str: line 1 column 1 (char 0)
Is that your sensor attributes result or is that the rest resource?
as suspected, provider returns a string, the rest are dicts
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
<tr><td>{{ name }}</td><td>
{% if value is mapping %}
{% for k, v in value.items() %}
{{ k }}: {{v }}</ br>
{% endfor %}
</td></tr>
{% endif %}
{%- endfor %}
@humble mortar ^
that's going to look shitty tho as a table
Maybe return the string in an else?
yah sure π€·ββοΈ
no clue what he wants
if he wants separate tables, he'll have to rework all the HTML
Rest resource
Sorta works there a few items with even more levels deep? https://imgur.com/a/NG9txAp
What does is mapping mean and how did that fix it?
I was going for something like this https://imgur.com/a/W7kzfHU
Just with a bit more data π
Hi. I have a trigger-based sensor. I would like write to its attributes a value with the key equal to the object_id of the trigger, Something like
trigger:
- platform: state
entity_id:
- sensor.bla1
- sensor.bla2
variables:
trigent: "{{trigger.to_state.object_id}}"
...
sensor:
attributes:
{{trigent}}_last_state: "{{trigger.to_state.state}}"
Is something like this allowed? If not, how can I work around it -- I would like to have a general template for an arbitrary number of monitored entities, which would save their individual state in the attributes with the attribute name generated by the template somehow. Or at least so that I could retrieve in the templeate for the state
Or maybe one could have just one attribute name fixed, with a dictionary as the attribute state?
mapping is a check to make sure something is a dictionary
Hi, why does this template not output a string into my local language (Dutch)
{{as_timestamp(now()) | timestamp_custom('%A %d %B')}}
output: "Wednesday 15 February"
Any idea if it's possible to get the "attribute" elevation, we have set for our Home?
Or maybe another way of asking: is it possile in a template to create a variable name based on a string stored in another variable -- sort of equivalent of python's exec
{%- macro writeline(key, input, indent='') %}
{%- if input is mapping %}
{%- if key %}
{{ indent }}{{ key }}:
{%- endif %}
{%- for k, v in input.items() %}
{{ indent + ' '}}{{ writeline(k, v, indent + ' ') }}
{%- endfor %}
{%- elif input is iterable and input is not string %}
{%- if key %}
{{ indent }}{{ key }}:
{%- endif %}
{%- for v in input %}
{{ indent }}{{ writeline('', v, indent + ' ') }}
{%- endfor %}
{%- else %}
{{ indent }}{{ key }}: {{ input }}</ br>
{%- endif %}
{%- endmacro %}
<table>
<tr align="left"><th>Item</th><th>Stat</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
<tr><td>{{ name }}</td><td>
{{ writeline('', value, '') }}
</td></tr>
{%- endfor %}
</table>
that uses a recursive macro with no safety built in, it shouldn't iterate forever but it can if this go wrong
anyways, it will traverse whatever shape you throw at it
looks like there's issues with the func, I'll have to look at it in a bit
I guess it's because the python version is provided as a list
"version": [3, 7, 3, "final", 0]
The ui editor also mangled the code word wrapped some of it.
https://imgur.com/a/oDhkOhz removed all the weirdness and put the word "first line" to see where the markdown box starts
Seems to mangle it every time you save and then click code editor again π¦
There was also a bunch of carriage returns throughout the macro stuff removed it then it closed up the gap a bit I think the rest is table padding removed the table
Another idea: if I set a variable to be a dictionary within a template, can I update its values somehow. Whatever I try fails.
how can I make a template sensor that updates every day?
Trigger based template sensors are your friends
No, you cannot modify data structures once created. You need to create a new data structure based on the original
That would be fine for me but how would I create a new dictionary with a particular value replaced? No dict merge etc seems to work?
something like:
{% set orig_dict = {"foo": "bar", "floop": "blah"} %}
{{ dict(orig_dict.items(), **{"foo": "new"}) }}
{
"foo": "new",
"floop": "blah"
}
A brilliant. Thanks0.!
I confess that I keep an example in a note because I can never come up with it when I need it
Is there a way to use value_json without referencing the name of the key, as in which element number?
{'Cords, Chargers, and Printer Cartridges': {'category': 'rotating', 'quantity': 1}, 'Batteries': {'category': 'standard', 'quantity': 1}, 'Plastic Film': {'category': 'standard', 'quantity': 1}, 'Light Bulbs': {'category': 'standard', 'quantity': 1}, 'Threads': {'category': 'standard', 'quantity': 1}}
I've got this attribute where the first element will change every 2 weeks to a new named category
This Ridwell integration has some of the worst sensor attribute formatting I've seen
I suppose I could just regex it out
Hi All,
I have maybe a stupid question.
I want to integrate some of Matthias dashboards ideas in my dashboard.
I have a lovelace UI dashboard.*
I have copied the button_cards_templates dir + content in the config dir of my HAS.
There is a light.yaml template in there...
But i still get the button-card template light not found...
I looked but i have no ui-lovelace.yaml to put the include in it..and it seems correct as i use UI mode
So i found on internet that you need to add it into the dashboard itself by going into edit and raw configuration editor...
But whatever i put into there, i or gives me an invalid syntax error or it does not work either...
Do i need to put it into that raw configuration error or somewhere else?
What is the correct syntax to put it into there?
Any help would be much appreciated...already strugeling for days with this...
Probably off topic for the templates channel based on your question, but you'll likely want to install HACS and then use that to install the frontend addon button-card
thats all done....i can add the card etc...i'm only stuck on the template includes....because this works apparently different in yaml versus ui mode
Is it some kind of template light? I'm not even sure what you're attempting to run exactly
It actually works without .items()
Sorry if i was not clear...
In a dashboard i have this custom_button_card
- type: custom:button-card
entity: light.bureau
name: Bureau
template:- light
- icon_hue
Light and icon_hie are button_card_templates....
I have all those in a seperate dir with a lot of yaml files...
Instead of putting the code via the raw configuration editor like this in the dashboard itself...
..
button_card_templates:
light:
double_tap_action:
action: fire-dom-event
browser_mod:
service: browser_mod.popup
data:
title: |
[[[
return !entity || entity.attributes.friendly_name;
]]]
card_mod:
etc....
because it's a lot of code i want to reuse in different dashboards., I am looking in how to put !include-dir all those files that i also have as seperate yaml files.....
The only way i got it working is to put everything into the raw configuration editor....But it's so messy....
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
That's basically what the button card tells you to do
If you want ui-lovelace.yaml you'll have to make it manually and configure HA to use it
That was the old way to do custom dashboards before they had UI management
Hey, any good idea for the following. I have a button, that when pressed should grab a datetime of a sensor, and use that for triggering an automation when that time occurs?
Your button can call a script to copy the datetime to an input_datetime. Your automation can use that input_datetime as a time trigger.
So easy, will give it a shot. Thx
I guess it doesn't even need to be a script, even just a call service could probably do it.
@thorny snow , hm.. not really going my way this. https://pastebin.com/0F5Jij8H <-- Code
Results in error
Failed to call service input_datetime/set_datetime. expected float for dictionary value @ data['timestamp']
The output of that state_attr is "2023-02-16 02:00"
Gotcha
but timestamp usually wants a float
so...
as_timestamp(state_attr('binary_sensor.nordpool_planner_activate_dishwasher', 'starts_at'))
but I do have to ask, is that timestamp local time or UTC?
Localtime
because it will be off by your timezone if it's local
Based on my geographic area
ok
state_attr('binary_sensor.nordpool_planner_activate_dishwasher', 'starts_at') | as_datetime | as_local | as_timestamp
service: input_datetime.set_datetime
data:
timestamp: >-
state_attr('binary_sensor.nordpool_planner_activate_dishwasher',
'starts_at') | as_datetime | as_local | as_timestamp
if you set the datetime field instead of the timestamp field, you can omit the as_timestamp
Gets me an error still, now trying with a script
Yeah, missed the {{ but still getting an error with about float
Just running a script now
then there should be an error in your logs related to the template
Would be good to set a target to begin with ^^
ah yes π
But still getting error π¦
DISKMASKIN - Set start: Error executing script. Invalid data for call_service at pos 1: expected float for dictionary value @ data['timestamp']
Most recent
test it in the template editor to see for yourself
Oh, just did it
Misslyckades med att anropa tjΓ€nsten input_datetime.set_datetime. expected float for dictionary value @ data['timestamp']. Got None
that can't be the result of the template editor as it doesn't validate yaml
Sure is
developer tools -> template?
.. yeah
Was using the service tab
service: input_datetime.set_datetime
target:
entity_id: input_datetime.diskmaskin_starttid
data:
timestamp: >-
2023-02-16 02:00:00+01:00
Why the +01:00? Because looking at Dev tools - states it doesn't show that
that's a datetime object
with your local timezone applied
and you put this template in the editor?
{{ state_attr('binary_sensor.nordpool_planner_activate_dishwasher', 'starts_at') | as_datetime | as_local | as_timestamp }}
Didn't have "as_timestamp"
Now it outputs:
service: input_datetime.set_datetime
target:
entity_id: input_datetime.diskmaskin_starttid
data:
timestamp: >-
1676509200.0
alright, that's a float
Yeah
np
hi! Can someone be a second pair of eyes for me? estimated_island_battery_total_energy is calculating properly but estimated_battery_total_energy is showing unavailable. http://pastie.org/p/3TDaQhCwiw29LosX6nFh3e
you're using multiline yaml notation and wrapping your template in quotes. Use one or the other, not both.
also keep in mind that you may have issues at startup if your sensors are not numbers
your source sensors, i.e. bank1,2 and3
How to return integer in template?
Is there a way to specify a default when calling state()?
change float to float(0) to supply 0 as a default
sweet! Thank you. One final question -- I'm trying to specify state_class on these items but I'm getting an error of Invalid config for [sensor.template]: [state_class] is an invalid option for [sensor.template]. Check: sensor.template->sensors->estimated_battery_energy_bank_1->state_class. however, the docs show that state_class is valid in the template integration.
You have to use the new style template sensors to use state_class
you're using the legacy style
oh, ok, I'll look up how to migrate over. Thank you.
With the new format, I see that the root of the yaml is template -- I use !include_... macros in configuration.yaml. Any pointers on how to maintain that pattern in the new format? I was thinking template: !include_dir_list templates/ and then having a path of ./templates/sensors/xyz.yaml -- is that accurate?
You can do that by using
template: !include_dir_merge_list template
keep in mind this is a list, and not a named
you can't use named because of the nature of the template: yaml
then in that folder (config\template), make sure you list out your entities inside your files, here's an example of one of mine:
- binary_sensor:
- unique_id: washer_status
name: Washer Status
device_class: power
state: >
{{ is_state('input_boolean.washer', 'on') }}
attributes:
template: energy
- unique_id: announce_washer
name: Announce Washer
device_class: door
state: >
{{ is_state('switch.announce_washer', 'on') }}
attributes:
template: energy
- unique_id: dryer_status
name: Dryer Status
device_class: door
state: >
{{ is_state('input_boolean.dryer', 'on') }}
attributes:
template: energy
- unique_id: announce_dryer
name: Announce Dryer
device_class: door
state: >
{{ is_state('switch.announce_dryer', 'on') }}
attributes:
template: energy
- sensor:
- unique_id: energy_terrif
name: Energy Terrif
state: "0.053080"
unit_of_measurement: $/kWh
I have created the following template to create a sensor that changes the temperature sensor being targeted by a thermostat depending on the time of the day, then have the generic_thermostat set it as the targeted sensor. The developer tools template is returning the named sensor, and I believe it should return a temperature of that sensor instead (integer). Any ideas on how to fix this?
{% if ((states.sensor.time.state > '19:30') and (states.sensor.time.state < '00:00')) or ((states.sensor.time.state > '00:00') and (states.sensor.time.state < '06:30')) %}
sensor.master_air_temperature
{% else %}
sensor.kitchen_air_temperature
{% endif %}
If you want to return the state of the temp sensor and not the entity_id, use {{ states('sensor.xxx') }}
And to simplify the template even more:
{% if now() > today_at('06:30') and now() < today_at('19:30') %}
{{ states('sensor.kitchen...') }}
{% else %}
{{ states('sensor.master...') }}
{% endif %}
Thanks! That seems to have worked. Now just trying to figure out how to get my temperature sensors to only report when they've changed lol
What do you mean? Entities only report when they change state.
I think i figured it out. My sensors were losing battery quite quickly but I just went in and saw that they were reporting every minute with the reporting threshold set to 10 degrees. I set the reporting interval to 0 and the threshold to 10 (1 deg) and it seems to work now.
Thanks for the help though.
π
first time making / dealing with a template. I've used a drop down menu, and that may be suitable, but I'd like a template sensor that can tell if me or my wife's phone are in an MQTT room. Is there a guide or something I could copy to get my feet wet?
It does not trigger the yes received automation.
That's strange, because the trigger is now even more generic
so if it triggered before, it should also now
How can I protect myself from a possibly missing attribute in a template? I am intending to write a sensor which will eventually populate the attribute, but in the initial state it has not done so. The state then depends on the value of this attribute. So I want something like set attr = this.attributes.attr when in the initial state attr is not there (it's not None, the key is not there yet), which results in UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'attr'.
possible answer -- you can test if this.attributes.attr is defined and this doesn't bomb out
trying to replicate the logic Bram uses in his weather card, I have this now, which, besides some defaults to be added, works ok with a big caveat: it has not yet implemented the ..weatherIconsDay https://github.com/bramkragten/weather-card/blob/8773e031775f58ebfabdfbbfb56907db4a7aed0e/dist/weather-card.js#L25 yet. Ofc, this is required to map the states, but so far I have not encountered a jinja way to do so. I think... can we? Or do I have to copy the entire map verbosely, and only change the night icons.?
Hi, i got a value_template from MQTT is there a way to get all subtopics in a list?
I could probably catch it with a condition: {% set condition = states('weather.buienradar') %} {% if states('sun.sun') == "below_horizon" and condition in weatherIconsNight %} {{weatherIconsNight[condition]}}.svg {% else %} {{weatherIconsDay[condition]}}.svg {% endif %} .... but still would like to know if we can call the mapper inside the second, and override it on certain states
Any thoughts on what I am doing wrong here?
{{ strptime('2023-02-16 17:15:57.390622+11:00', '%Y-%m-%d %H:%M:%S.%f+%z') }}
ValueError: Template error: strptime got invalid input '2023-02-16 17:15:57.390622+11:00' when rendering template
you left out the important part: but no default was specified π
sure, you can specify one and it just returns the default.. If the strptime works, I don't need a default.
This works, so it just does not like the timezone offset at the end for some reason.
{{ strptime('2023-02-16 17:15:57.390622', '%Y-%m-%d %H:%M:%S.%f') }}
oohhh
got it
{{ strptime('2023-02-16 17:15:57.390622+1100', '%Y-%m-%d %H:%M:%S.%f%z') }}
I was adding in the + when it was not needed. π
was just typing that.... sorry for being slower than you..
btw, if you past code here, use the <> button after selecting the text, or backticks before and after the text like {{ strptime('2023-02-16 17:15:57.390622+1100', '%Y-%m-%d %H:%M:%S.%f%z') }}
yeah, cool. Can do.
I am once again looking for a pointer towards the right guide / post: I have a drop down list on the interface to select and what time of day exterior lights should turn on. This varies frequently and I am not making friends with the state of the sun approach I had so-far. So I want to be able to select the trigger time in the UI via drop-down. I have found how I can make a drop down list item a condition for an automation, I have not seen it to make it a trigger? Simple example would be I select 4PM on the drop down and from there on out the automation triggers as of 4. If I select 5PM the day thereafter the automation triggers at 5 there on out
just use an input_datetime with only time set, and use that in a time trigger. No templates needed.
But then how do I link the drop-down to the automation?
just use the datetime as the at option
trigger:
- platform: time
at: input_datetime.whatever_you_name_it
all covered in the trigger docs
Okay perfect, will test. Thanks a lot
I'm trying to pass the entity_id of a media player into a script and get the volume level but I can't get it to work. Is this possible?
variables:
mediaplayer_state: '{{ states("{{ media_player_target}}") }}'
you are nesting templates
Yes, is that not allowed?
if media_player_target is a variable you defined somewhere, you can just refer to it in another template:
variables:
mediaplayer_state: '{{ states(media_player_target) }}'
And no, that is not the way it works π
Thank you @marble jackal !
good day! I have a google mini in my shed, buts its not always on (runs off solar power), how can I put an availability condition so that I don't always get an error thrown in my logs. Something like this?
data:
availability: >
{{ state('media_player.shed_speaker') not in [None, 'unknown', 'unavailable'] }}
entity_id:
- media_player.shed_speaker
message: "{{ message }}"
ah, do a condition in the previous step
- "{{ state('media_player.shed_speaker') not in [None, 'unknown', 'unavailable'] }}"
- service: tts.cloud_say
data:
entity_id:
- media_player.shed_speaker
message: "{{ message }}"
just be aware, if that condition is false it'll stop the whole automation action sequence and nothing executes after it
so you can use an if, if you have more stuff after it.. or change the order as necessary
also, that condition is condition short hand, you can use the more readable and verbose:
- condition: not
conditions:
- condition: state
entity_id: media_player.shed_speaker
state:
- None
- "unknown"
- "unavailable"
- service: tts.cloud_say
data:
entity_id:
- media_player.shed_speaker
message: "{{ message }}"
@floral steeple ^^
@ruby vault hey thanks, that would work...I'll have to reorder it so its the last excecution...or maybe a if-then-else as you suggested, but could make it overly complicated
@ruby vault ok heres the whole automation
http://pastie.org/p/0TSuuXc2amzDqbBjlVLuah
i used if then
yeah, well the else is optional, so just an
- if:
- "{{ state('media_player.shed_speaker') not in [None, 'unknown', 'unavailable'] }}"
then:
- service: tts.cloud_say
data:
entity_id:
- media_player.shed_speaker
message: "{{ message }}"
will do
so that way that way the automation stops gracefully
perfect! I did it exactly like you
yeah, ezpz
actually, the GUI added some extra fluff
- condition: template
value_template:
I guess I could keep it
yeah, tis fine. It just another way
awesome, thanks for your help!
I'm in MST...is everyone else sleeping lol
oh, wow.. Ok, that works. How is yesterday afternoon? π
well, only 0910 but yeah, looking to be a fantastic day
π€£
Hi! I need to send a json message to mqtt using a template. The idea is to obtain a message like this:
{"value":2590629792,"protocol":32,"length":32,"delay":423}
but using a value that is stored in a helper. I have tried this:
{{{"value":int(states('input_number.mqttto433code')),"protocol":32,"length":32,"delay":423}}}
and the templeate editor converts it properly, but when trying to send it, it raises the error: "failed to call service script/velocidad_ventilador. Value should be a string for dictionary value @ data['payload_template'].
How can I fix it?
No way to know for sure when you don't share the complete service call, but my first guess would be that you didn't wrap your template in quotes
bingo! thanks @marble jackal
still doing something wrong on the mqtt publish. pastebin is https://pastebin.com/Wcnsq8U9 and mqtt publish is in line 81
Remove the outside quotes, add a > after the colon and move the template to the next line, indented 2 spaces from payload_template
like this:
payload_template: >
{{{"value":int(states('input_number.mqttto433code')),"protocol":32,"length":32,"delay":423}}}
dont know why the spaces in the second line are not showing up
Does jinja have 3 braces?
No, heβs outputting a dictionary
2 braces for the template, 1 brace for the dictionary
I think thatβs correct but Iβm on mobile so it looks weird
yeah, it does not fail
π
thanks @mighty ledge
Np
FYI thatβs called multiline indicator
When you do single line templates you need to wrap the single line in quotes. But then you run into quoting issues
So you can skirt around those issues by making it a multiline template
well, in this case you could've also used double quotes for "input_nuberm.mqtto433code" and then wrap the template in single quotes
that's why it is important to be consistent with the quotes inside the template π
Ya, but thatβs too much to explain when youβre on mobile π€£
I took the lazy way out
this is the other option then? payload_template: '{{{"value":int(states("input_number.mqttto433code")),"protocol":32,"length":32,"delay":423}}}'
yes
I would also suggest to add some spaces to increase readability
and another option is:
payload_template: '{{ dict(value = states("input_number.mqttto433code") | int, protocol = 32, length = 32, delay = 423) }}'
don't know why, but it's converting the double qoutes to single quotes and the message does not work
if i send the message ussing mqtt explorer this is it:
{
"value": 2774917024,
"protocol": 32,
"length": 32,
"delay": 423
}
if i send it with the template is like this:
{'value': 2778324896, 'protocol': 32, 'length': 32, 'delay': 423}
If i send the message using mqtt explorer, the program works (this is for open mqtt gateway)
I don't use mqtt myself, I expect it expects a dict, and not a json string. Do you know that @mighty ledge
Hello, i currently have a problem with the last_updated state.
Why do those two not give the same value:
{{ states.sensor.smart_socket_16a_5_power.last_updated }}
{{ state_attr('sensor.smart_socket_16a_5_power', 'last_updated') }}
The first one gives the wanted value, but the second one returns None.
And states('sensor.smart_socket_16a_5_power').last_updated throws an error.
You can only use the first
it's not an attribute of the entity
Oh okay, thank you.
Hey guys, I am having a little trouble with mqtt hvac, I have set it up in my configuration.yaml, but I get this error when I update the temperature using the thermostat card:
Failed to call service climate/set_temperature. UndefinedError: 'dict object' has no attribute 'unknown'.
the relevent part of my configuration.yaml is here: https://pastebin.com/ipjZFkAm
and I think the problem lies in my templates :S
{% set modes = { 'off': '02', 'heat': '01' } %}
{% set fan_modes = { 'off': '01', 'low': '02', 'high': '03', 'anti-frost': '04'} %}
{{ ["F1F1", "0210", modes[states('climate.panel_heater_office')], "00", "02001900", fan_modes[state_attr('climate.panel_heater_office', 'fan_mode')], ('%#x' % (value | int))[2:], "0100", "00", "01000001", (('%#x' % ( 48 + (modes[states('climate.panel_heater_office')] | int) + (fan_modes[state_attr('climate.panel_heater_office', 'fan_mode')] | int) + (value | int)))[2:] | upper), "7E"] | join }}
My guess would be that states('climate.panel_heater_office') results in unknown and so you are now trying to find modes.unknown which is not a valid attribute
It expects json
@marble jackal it works! thanks a bunch. not sure how i missed that in my copy/paste frenzy
@marble jackal @mighty ledge I'm an idiot. I was sending the data to the incorrect topic 
That would also help
π€£ sometimes I would love to be able to read and comprehend the text at the same time
I think i finally found my issue, i think im not using operators right? if i put (1 > 0) in a template it says condition did not pass?
how do i compare things?
Which issue are you referring to here?
uhm, some long time ago i had an issue with the dev tools not giving same result as template condition
this ^
π
Okay
Are you referring to the condition checker in the GUI here? I think that's still broken for remplate condtions
oh, is it broken? π€
i mean
trace shows same result
Executed: 17 February 2023 at 14:07:06
Result:
result: false
if:
- condition: template
value_template: (1 > 0)
dev tools does show True
whats going on? π
I am trying for the first time to use YAML anchors for some template sensors. For example (I'm cutting the complicated parts of these):
- sensor:
- &cumulator_sensor
name: Electricity total Energy cumulative
state_class: total_increasing
unique_id: "roigjoreofffifnofnvo"
state: >- ....
and then I create a second sensor in the same file which is being included into config.yaml through !include_dir_merge_list templates/
- sensor:
- <<: *cumulator_sensor
name: Electricity total Energy
unique_id: "roigjoreoifnofnvo"
I get an error that my name and unique_id are duplicated. The second sensor works fine seemingly, but am I doing something non-legit?
Hey folks, kindly redirect me if this isn't the right place to ask, but I'm wondering if it's possible to use a template to redefine how a service works.
For instance: I have five IKEA Frytur blinds that I am adding to a picture-elements dashboard, so if I want to just tap on the icon to call-service cover.toggle that would be fine except that I want the open behaviour of cover.toggle to cover.set_cover_position with a value of 95% since the blinds don't like being pulled up into the body of the roller. I had been using 3D printed standoffs to hack this, but then I set all my other automations to only open to 95% and have removed the standoffs.
Look at template cover
Looks promising, thank you.
That's not a jinja template
a jinja templates needs to be wrapped {{ and }}
if:
- condition: template
value_template: "{{ 1 > 0 }}"
It also needs quotes if you use the single line notation
how to access/ get value of the previous valid state of an entity?
so that my automation can have a condition to not trigger if previous value is the same ..
without the need of a helper
I've just come up this a sollution for this. Have a look here:
https://community.home-assistant.io/t/template-sensor-with-last-good-value-stored-in-attribute/535581
I store it in an attribute
i mean i thuaght of this, but i remember there was a way to get the previous valid value as it will be very crucial to most of the automations.
You don't need to store the previous state in a sensor
You can just compare trigger.from_state.state with trigger.to_state.state
but... If you set up a state trigger with a blank to: or from: it will only trigger if the state changed, so not if only attributes changed
But this fails whenver you end up with an unknown/unavailable state and you then have no access to a last good one that you might want to compare with
π€¦ββοΈ i see what i did there, thanks
i have a sensor that comes in as a number, this is the condition to resolve this matter. what do you guys think
{{ (states.sensor.numeric1.state| int is number) and (trigger.from_state.state| int is number) }}
You can simplify that to {{ states('sensor.numeric1') | is_number and trigger.from_state.state | is_number }}
yes agreed π
whoops, replied to the wrong post π
{{states('input_number.targettempbedroom')|float+0.3}} this should work for incrementing a number on the fly right?
service: climate.set_temperature
data:
target_temp_high: {{states('input_number.targettempbedroom')|float+0.3}}
target_temp_low: {{states('input_number.targettempbedroom')|float-0.3}}
target:
entity_id: climate.bang_bang_climate_controller
like that?
cause it gives me Error running action expected float for dictionary value @ data['target_temp_high']. Got None expected float for dictionary value @ data['target_temp_low']. Got None
You need to surround your template in quotes
I need to define a sensor that is a division of 2 other sensors. Is it not possible to define this via the home assistant "Helper" UI? Or do I have to define it via yaml?
I assumed it was going to be either "Combine the state of several sensors" or "Derivative sensor" but neither has division operators or is limited to 1 input sensor.
No, divison is not an option in those, you need to define a template sensor in yaml for that
Am I allows to use soemthign like states(this) to protect mysellf from unavailable or just this.state inside a template sensor state.
states(this.entity_id) works
but not states(this)
or this.get('state', 'unknown')
or this.state | default('unknown')
I have a problem with a template, which goes to unavailable every time I reload the templates. I think I've boiled it down to this:
- sensor:
- name: Electricity total Energy Tester
unique_id: "erigmehpoigem"
state: >-
{% set current = states(this.entity_id)%}
{{current}}
Is there some way of protecting myself here?
I just learned that there is a legacy definition for sensor template that I've been using an HA docs recommends the modern format. However, I'm getting tripped up on identation. In my sensors.yaml file, I have this currently and exact identation. What is the "modern" format version of this?
- platform: template
sensors:
attic_humidity:
unique_id: sensor.attic_humidity
value_template: "{{ state_attr('climate.attic', 'current_humidity') }}"
unit_of_measurement: "%"
friendly_name: "Attic Humidity"
device_class: humidity
the new is:
template:
- sensor:
name: Attic humidity
state: "{{state_attr('climate.attic', 'current_humidity') }}"
where the template key is in configuration.yaml -- so it dosn't go into the sensors key
hey all, this little if-then part leads to an error: Error: In 'template' condition: UndefinedError: 'state' is undefined
- condition: template
value_template: >-
"{{ state('media_player.shed_speaker') not in [None, 'unknown',
'unavailable'] }}"
then:
- service: tts.cloud_say
data:
entity_id:
- media_player.shed_speaker
message: '{{ message }}'
Not sure why, basically, I don't want it to send TTS to that speaker is if not avaiable.
ok...its supposed to be states 
what am I doing wrong in this yaml file?
template:
sensor:
unique_id: tower_array_used_percentage:
name: Tower Array Used Percentage
state: >-
{{ ((states('sensor.tower_array_used') | float / states('sensor.tower_array_total') | float) *100) | round(2) }}
unit_of_measurement: '%'
~~vs code validation errors galore: https://i.imgur.com/LQ8lwMj.jpg~~
(Just learned the vs code validation errors are annoyingly likely false positives.. so ignore this last part. Yaml still fails to load with errors in my logs like this:
while scanning for the next token found character '%' that cannot start any token in "/config/sensors.yaml", line 14, column 28
mapping values are not allowed here in "/config/sensors.yaml", line 9, column 12
Why would you say VS Code errors are false positives
How are you including that file
Seeing convos like this: https://github.com/keesschollaart81/vscode-home-assistant/issues/1866
That issue is closed as fixed
sensor: !include sensors.yaml
But the file you linked is concerned w/ template:
Right.. but i've had this issue before where validation complained about things like this due to the schema being out of sync.. maybe i'm wrong in this case.
Here is an example of a modern template sensor declaration https://www.home-assistant.io/integrations/template/#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors
If you want to split it like you did sensor:
template: !include template.yaml could go in your config
and then you pick up from line 2
Oh i see.. i need to include with template: !include template.yaml in order to have it evaluate template sensors.
I've historically done my inclusion in my config yaml like this:
automation: !include automations.yaml
binary_sensor: !include sensors_binary.yaml
climate: !include climate.yaml
group: !include groups.yaml
light: !include lights.yaml
media_player: !include media_players.yaml
notify: !include notify.yaml
sensor: !include sensors.yaml
script: !include scripts.yaml
switch: !include switches.yaml
zone: !include zones.yaml
Gotcha, that's fine, you'll just need to add template to your list there w/ a new file
- data:
message: >-
Outside Laundry Door is open
title: Laundry
service: notify.jurgen,notify.megan```
is this valid?
and double service line
Oh i see i need to include with
2023-02-18 11:24:59.318 ERROR (MainThread) [homeassistant.components.automation] Automation with alias 'Laundry Outside Door left open and nobody home' could not be validated and has been disabled: Service notify.jurgen,notify.megan does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']. Got 'notify.jurgen,notify.megan'
well, that answers that. π
no, it is not. you can create a notify group, though
I am trying to do this with an automation
- service: notify.all
data:
title: person detected
message: no one at home
data:
image: |-
{% if trigger.entity_id == "binary_sensor.back_person_occupancy" %}
/api/camera_proxy/camera.back_person
{% elif trigger.entity_id == "binary_sensor.front_person_occupancy") %}
/api/camera_proxy/camera.front_person
{% else %}
/api/camera_proxy/camera.webcam_person
{% endif %}
but I keep getting the following error:
2023-02-18 16:42:43.412 ERROR (MainThread) [homeassistant.components.automation] Automation with alias 'someone appraoch the house and no one is home' could not be validated and has been disabled: template value should be a string for dictionary value @ data['action'][0]['data']. Got OrderedDict([('title', 'person detected'), ('message', 'no one at home'), ('data', OrderedDict([('image', '{% if trigger.entity_id == "binary_sensor.back_person_occupancy" %}\n /api/camera_proxy/camera.back_person\n{% elif trigger.entity_id == "binary_sensor.front_person_occupancy") %}\n /api/camera_proxy/camera.front_person\n{% else %}\n /api/camera_proxy/camera.webcam_person\n{% endif %}')]))])
2023-02-18 16:42:44.733 ERROR (MainThread) [homeassistant.components.automation] Automation with alias 'someone appraoch the house and no one is home' could not be validated and has been disabled: template value should be a string for dictionary value @ data['action'][0]['data']. Got OrderedDict([('title', 'person detected'), ('message', 'no one at home'), ('data', OrderedDict([('image', '{% if trigger.entity_id == "binary_sensor.back_person_occupancy" %}\n /api/camera_proxy/camera.back_person\n{% elif trigger.entity_id == "binary_sensor.front_person_occupancy") %}\n /api/camera_proxy/camera.front_person\n{% else %}\n /api/camera_proxy/camera.webcam_person\n{% endif %}')]))])
I am not following its problem. :\
ah, there is a rogue ) in tehre
argh, 30mins on a rogue ), the error was totally throwing me
Hi guys, I have a motion sensor which goes to 'on' state when motion is detected. It stays in that state for a minimum of 10 seconds. I however have a use case where I'm working a 'light follow' mode where I want to know if motion was very recently triggered (recent as in the last 2 seconds, in order for the follow mode to work correctly). Because of the minimum 10 seconds state on my motion sensor, the best resolution I can get is 10 seconds which is too high, all I can know is that the sensor was triggered sometime in the last 10 seconds but no lower.
I set up a template sensor in my configuration.yaml that aims to give me what I want by looking at the last_updated key on the sensor, however it seems that the template sensors don't update frequently enough either and don't work as expected. Is there some docs on how often templated sensors update. Basically this block of template works in my developer tools section if i manually ensure the template is retriggered (by typing any characters in the dev template window), but it won't automatically update fast enough when in the configuration.yaml or when in the dev tools window (and when not helped along by typing characters to get it to refresh).
The dev tools say the following, but I assume keys like last_updated are not part of that listening?
This template listens for the following state changed events:
Entity: binary_sensor.motion_now_in_living_room
@tribal cedar The problem with your template is that now() or utcnow() are only evaluated on every whole minute, so your binary sensor will turn off somewhere between 2 second and 1:02 minuten after being turned on
A better solution will be to create a trigger based sensor which turns on when your motion sensor does, and has an auto turn_off after 2 seconds
In any case your template is overly complicated
This would do the exact same (inaccurate) thing as your current sensor
{%- set sensor = 'binary_sensor.motion_now_in_living_room' -%}
{{ is_state(sensor, 'on') and now() - states[sensor].last_changed < timedelta(seconds=2) }}
But what will work
template:
- trigger:
- platform: state
entity_id: binary_sensor.motion_now_in_living_room
to: "on"
binary_sensor:
- unique_id: motion_sensor_turned_on_last_2_seconds
name: Motion sensor turned on in last 2 seconds
state: "{{ True }}"
auto_off: "00:00:02"
I got a text parsed template with lots of else if.
How can I make the script output one line
@cosmic hamlet I converted your message into a file since it's above 15 lines :+1:
oh when i get it in a template the \n are removed
Hi
Is it possible to get secret value inside template (template entities)?
Like equivalent of !secrets from yaml?
You can probably do something unorthodox like setting a variable in the trigger of a template sensor, referencing the secret and then use the variable in the template
That's the only way I can think of. The short answer is no, you can't access secrets directly from a template
@analog mulch @inner mesa ok, thanks for the reply
Hello there, I have an issue with one of my scripts that launched that action at 1AM this morning
service: climate.set_temperature
data:
target_temp_low: "{{ states('input_number.temperature_confort')| float(0) +1 }}"
target_temp_high: "{{ states('input_number.temperature_max_mode_nuit')| float(0) }}"
hvac_mode: heat_cool
target:
entity_id: climate.nest
the trace tells that it was done, but the Nest value did not change
is there any way to check and retry after the first attempt ?
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Please edit your message and format it as code
I think I am dumb π
GRRR canadian Keyboard π
You can copy them from the bot message if you can't find the right character on your keyboard
that's what I did, thanks for your help
You can use a repeat with a delay in it which performs it every x seconds until the data reported by the entity matches your requested data
how can I check that "the entity matches your requested data" part ?
is it normal that there is no check ? it's just a fire and forget ?
Yep, that's what it does
ho ...
Well, if the integration reports an error or warning, it will log it
I learned something
I don't have any trace at all, except the command was sent
but in log, no change was done to Nest
I did exactly the same commanda 2h later that worked
I really think I would need to achieve what you proposed
thanks, I will check that
hi, How can I make an exception if the state of the binary sensor is unknown so it won't blink red (which is currently does)
http://pastie.org/p/0KiLdzeom3y8hvz6QTmHhs
Thanks.
Hey all, I'm getting an error in my logs about a template. Not sure where to even start to track this one down. Here's the log entry:
Logger: homeassistant.helpers.template
Source: helpers/template.py:575
First occurred: February 14, 2023 at 9:50:46 PM (5232 occurrences)
Last logged: 11:58:50 AM
Template variable warning: 'user' is undefined when rendering '{{user}}'
Seems clear enough
I don't recall setting any type of a templte up for use with a user...
Your blinking animation is tagged to the default, which will match whenever the state doesn't match any other value configured in your card. Just declare another state specifically for on or unavailable.
Do you mean under state:
- icon: mdi:water
styles:
card:
- height: 100px
icon:
- width: 45%
- opacity: 0.5
name:
- padding: 5px 0px
- font-size: 15px
- text-overflow: unset
- white-space: unset
- word-break: break-word
value: 'unknown'
EDIT:
It worked, thanks.
im trying to get mute and unmute working in a mushroom template chip
https://hastebin.com/share/yoqejeloho.yaml
I need `` is_volume_muted: true ` templated like i did with the iconcolor above, but somehow i cannot get it to work?
tap_action should do both
is the servicecall inside a frontend item templatable?
https://hastebin.com/share/qesisunazi.yaml
HA says nooooo
You can't use templates in a tap action
You can call a script and do the logic in there
But this is always wrong
First, you don't need to do == true as it will already return true or false itself
data:
is_volume_muted: >
{% if state_attr('media_player.receiver_huiskamer', 'is_volume_muted') %}
false
{%else%}
true
{%endif%}
that looks better then my hacked together version π
You can't template a whole key: value pair like you were doing
You need to return a dict then, but it's easier to just template the value
i thought it was going to write the whole string
you are sooo correct... yet again π
Yes, but that's the issue, it expects a dict, not a string
ill pass this in a script and go from there
And you need to reverse the logic of the boolean value to unmute when it's muted
i was thinking a IF THEN in the script
IF muted A. Else B
or a choose. both should work
And you can simplify it to:
data:
is_volume_muted: >
{{ iif(state_attr('media_player.receiver_huiskamer', 'is_volume_muted'), false, true }}
thats just shorthand right?
That's using the iif function
ill have a read about that. thx!
hello everyone,
I have an infrared transmitter that sends a temperature command to the air conditioning. for example I send 19 or 21 or I increase the FAN. I would like to know if there is a thermostat integration that allows you to bind this command to a thermostat. I'm not talking about PID type integrations. THANKS !
@twin junco I converted your message into a file since it's above 15 lines :+1:
Is there a way I can create templated sensors, but in a loop. For each area I have I'm finding myself having copy/pasted a lot of templated sensors, with very little differences between them, usually an area name and an entity name differing only.
Hi, I am trying to help someone on the HA forum but what he is showing is beyond me.... an attribute is converted in python
from: '2023-02-19T00:00:00+00:00'
becomes
'from': datetime.datetime(2023, 2, 19, 0, 0, tzinfo=datetime.timezone.utc)
in his devtools > template .... any ideas from the specialists here?
Anyone know where I am going wrong? I have a group of lights I ALWAYS want to keep on but at night when we trigger the "good night" automation I have an action to call lights.off and entity is set to all. I want to turn off all "on" lights EXCEPT those in the helper group. This isn't working and shows one of the devices I don't want to come back.
| selectattr('state', 'eq', 'on')
| rejectattr('entity_id', 'in', expand('light.group_keep_on_lights'))
| rejectattr('attributes.entity_id', 'defined')
| map(attribute='entity_id')
| list
}}```
I am getting back ['light.dimmer_dry_contact_relay', 'light.great_room_fan_light'] but expect just ['light.great_room_fan_light']
I can use this:
| selectattr('state', 'eq', 'on')
| rejectattr('entity_id', 'in', expand('light.group_keep_on_lights'))
| rejectattr('entity_id', 'search', 'light.dimmer_dry_contact_relay')
| rejectattr('attributes.entity_id', 'defined')
| map(attribute='entity_id')
| list
}}```
But was hoping to use a group helper for wife factor.
Thanks for your help with this. I'm still struggling but will keep an eye out on the thread and happy to do any more testing required...
the expand function will give you a list of state objects, so that first rejectattr isn't going to match
state_attr('light.group_keep_on_lights', 'entity_id') will get you your entity_id list
@obtuse zephyr how do I filter those out of the final returned list?
{{ states.light
| selectattr('state', 'eq', 'on')
| rejectattr('entity_id', 'in', state_attr('light.group_keep_on_lights', 'entity_id'))
| rejectattr('attributes.entity_id', 'defined')
| map(attribute='entity_id')
| list
}}
Thanks!
you bet
@obtuse zephyr that is throwing TypeError: argument of type 'NoneType' is not iterable in the dev tools
What does {{ state_attr('light.group_keep_on_lights', 'entity_id') }} return
Null, that explains it
π
I mean there is an object in there.
That group has one device at the moment
I'd expect it to return the one device right?
Or do I need more than one to make the list work?
<template TemplateState(<state light.group_keep_on_lights=unavailable; supported_color_modes=[<ColorMode.ONOFF: 'onoff'>], icon=mdi:lightbulb-group, friendly_name=Group: Keep on lights, supported_features=LightEntityFeature.0 @ 2023-02-18T21:02:03.978964-05:00>)>
Yes, they are.
like... disconnected/unavailable?
If every device in a group is unavailable, that'll break like that
<template TemplateState(<state light.dimmer_dry_contact_relay=on; supported_color_modes=[<ColorMode.BRIGHTNESS: 'brightness'>], color_mode=brightness, brightness=255, friendly_name=Richie Fan Light, supported_features=LightEntityFeature.TRANSITION @ 2023-02-18T21:51:40.548133-05:00>)>
The one device in that group is on
that light.dimmer_dry_contact_relay is the one device in that list atm
Well, you can see it's reporting unavailable for that group state though... which is odd
Yea, do I need to toggle the all entities in the group?
Or is HA returning a string when the template is expecting an array?
The problem isn't w/ the template currently... it's why the group is returning unavailable, when you say there's only 1 member of the group and that member is on
Is that a bug? π
Doubtful.... can you check your group options for that light group
Also, check your home-assistant.log
I have one member and hide members and all entities is off
Checking logs
Logs don't show anything but I don't have debug turned on.
Could you try creating another light group, same member just to see
@twin junco I converted your message into a file since it's above 15 lines :+1:
@obtuse zephyr trying now
That works...
Do I have a bad group or name in the old group?
I don't see anything wrong with it
Hmm, try restarting HA once, just to see if everything comes up ok
Ok.
Howdy, is it possible to use templates to create a group by defining a entitiy.id suffix, so all sensor.XXXX_foo (suffix foo) will be added automatically?
came up ok after restart
Good, odd though
You can't create an actual group...but, you could replicate with a template if you just want a read-only view of their aggregate state, like on/off
i'd like tu sum all power-sensors.
r/o would be ok for me. If i could use sum on all numeric values, it would be fine. But i don't know how to "replicate" it into a group?
You can come up w/ a template to grab all sensor entities that match a pattern and sum them, again, its not actually a group though
thanks for the help @obtuse zephyr!
You're welcome
I have a Helper entity that receives the number of steps I take from a Shortcut on iOS based on the steps my Apple Watch records. I don't take walks with my phone as it is my unwind time. This works and my entity shows as input_number.steps and a State of current steps. I thought I could create a value_template to hold these steps for historical purposes. I tried this -
http://pastie.org/p/0i3SOcP3rmNhWMDpWZEcBC
but upon adding to sensors.yaml the configuration check just spins and I see an error in the log. So looking for ideas on how to do this.
I'm not clear on what 'hold these steps for historical purposes' means. The HA database already does that for the original helper entity.
Then maybe I'm looking at it wrong. I see the history in the entity but when I try and use a history graph card the help entity is not listed. The steps in the helper entity are a state rather than attribute. I think that is why.
Doubtful
I'm more like confused than sceptical.
I suppose it's possible that the UI entity picker for that card doesn't let you choose an input_number entity, but I don't know why that would be the case
I'd ensure you set a unit_of_measurement
That seems to be missing one, and that tends to result in them not being graphable
Hi Tinkerer, fan of your work, you mean in the Helper?
There are other issues with your sensor.
entity_id was deprecated long ago, and your indentation is off
And it's the legacy format
Looks like it was copied from somewhere
Yeh, I was copying what I found on an old forum post.
Looks like the History Graph Card doesn't support attributes as I suspected. My idea to create the template sensor is still where I'm headed. Thanks.
That's indeed a python datetime tuple. You can use .isoformat() to convert it to a string. Then you need to use as_datetime to use it as a datetime again
I don't see where attributes enter into this at all. You're just trying to store and display a state, right?
My Helper is the entity that I write the data from iOS into. It is stored in that entity as an attribute. It's just a place I use to dump the Number.
It's an input_number, right?
Those don't have attributes that you set
Anyway, if you have a solution...
It's a Number helper.
It only has a state
Sorry I said attribute above, you are right, it is state.
Right, you're off in the weeds with the whole attribute thing
Nothing new for me. I chase rabbits down holes all day.
It's learning I tell myself.
Like I said, maybe the card doesn't let you pick an input_number for some reason. Or maybe you need a unit_of_measurement. The link to the docs I listed above show how to create a sensor with a unit
Thanks @inner mesa . I'll keep moving along.
Thanks and since I have never seen this behavior before, any pointers on where to find doc on this?
I only know it because I experienced it myself and asked here.
OK...thanks at least for the help!
Thatβs the string repr for a datetime object. Itβs a python thing for managing memory. If you donβt convert it to a string, it outputs the repr instead.
All python objects behave this way
So just use the str filter or isoformat
So, the first value is in the attributes as a for-me--seemingly normal date/time value ... and only after the template it becomes that one.... just never seen this before
fixed now
Because templates do type checking on the returned object and show you a friendly string version of its representation when it can figure out the type
aha, top!
When you have objects inside lists or dictionaries, it doesnβt try to type the listed objects, only the main list
So you get itβs string converted values, which are the repr
Which is usually meaningless in HA templates, but helpful when debugging in python
appreciating the explanation and already made a few comments in my 'notes' on templates π
@brittle jacinth I converted your message into a file since it's above 15 lines :+1:
what's throwing me here is the examples in the docs use the legacy yaml format vs the "modern" one mentioned in other pages https://www.home-assistant.io/docs/configuration/splitting_configuration/
You didn't make a list
See how the examples have a list: https://www.home-assistant.io/integrations/template/#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors
@inner mesa when you say "make a list" you mean with the hyphens?
Yes, as in the examples
PHEW. got it to work finally! thank you
@stable wagon I converted your message into a file since it's above 15 lines :+1:
Hello there! I am having a problem with a sensor in the energy dashboard, the sensor or the battery is not showing, I am using a Lynx battery from GoodWe, and an ES Inverter; in the hass website already say that could have problems with it, and that I must use a template for getting the values, but, I am really new in this, and I can't make it show, here is the template I created, but, first, it do not show the values, and 2nd, it don't show on the energy dashboard as an option.
- sensor:
- name: "Entrada Salida Bateria"
unit_of_measurement: "W"
device_class: "power"
unique_id: "sensor.battery_power_w"
state_class: "measurement"
state: >
{% set e_s_battery = states(sensor.battery_power) | float %}
Any idea of what can I do?
You are not outputting anything, the only thing you are doing now is defining a variable
And please format your code as code
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Done, do I make the outputting?
Oh! I see, sorry, I am really new, and learning while doing things... now i've don this :
- sensor:
- name: "Entrada Salida Bateria"
unit_of_measurement: "W"
device_class: "power"
unique_id: "sensor.battery_power_w"
state_class: "measurement"
state: >
{% set battery_w = states(sensor.battery_power) | float %}
{{ battery_w }}
But I suppose something is wrong with it, as the template data say, Unknown. Any help?
Hi. Is it possible to set an atrribute value for a trigger template sensor manually (or through some service) like I can with the state using developer tools? I only need it to survive until the next trigger so that the new attribute value gets picked up by the template.
You need quotes around the entity_id
Thank you!
it actually works! it's showing the information, anyway, is not showing on the energy dashboard, on the Battery section....
@thorny snow I converted your message into a file since it's above 15 lines :+1:
Sensor still not appear on battery in energy dashboard
Alright... I figured out how to use a service call to increment/decrement a counter, but how do I actually reference the counter itself to use it? I want to brighten lights very slowly by dividing by counter, so I tried:
{{ (state_attr('switch.adaptive_lighting_living_room','brightness_pct') | int) / counter.morninglightdivisor }}
Which, I'm sure everyone here is screaming the same thing as the templates tool is: 'counter' is undefined.
states('counter.whatever') | int
Ah. thank you.
Seems odd that everything is kept as a string and has to be converted to int, especially a "counter" that would be, by default, an integer, but, what do I know.
Okay trying to make it shorter. Why does my gauge card doesn't show the value from the template:
- type: gauge
entity: sensor.waschmaschine_program_progress
title: Waschmaschine
state_color: true
value_template: >-
{% set fortschritt = states('sensor.waschmaschine_program_progress') | float %}
{% if fortschritt <98 %} {{ states('sensor.waschmaschine_program_progress') }}
{% elif fortschritt >= 98 %} 100
{% else %} Maschine aus
{% endif %}
because type: gauge does not support templates. you can not just make it up....https://www.home-assistant.io/dashboards/gauge/#configuration-variables
You can't just put a value_template somewhere and expect it to work
I think I can π maybe i'll be disappointed then ;-). Okay so I have to establish a Template Sensor to make it work...
you can try to use card-templater on top of that...might be a bit fiddly to get it to work though
example using a helper
type: custom:card-templater
card:
type: gauge
entity: input_number.sunsetmin
entities:
- entity: input_number.sunsetmin
state_template: '{{ states("input_number.sunsetmin") | int(0) }}'
Trying to add the word "ago" to the end of this, but the way I have it, it only works when both hours an minutes are present. If it's under 1 hour, it doesn't include it. Where should I put the text so that it always shows up?
{% set text = [phrase(days,'day'),phrase(hours,'hour'),
phrase(minutes,'min')]
|select('!=','')|list|join(', ') %}
{% set last_comma = text.rfind(',') %}
{% if last_comma != -1 %}
{% set text = text[:last_comma] + ' and' + text[last_comma + 1:] + ' ago' %}
{% endif %}
{{text}}
add it to the text variable outside the if
or just make the last line {{ text ~ ' ago' }}
Is there a way to list all the entities that belong to a given zwave device using a template?
I have this trigger data in an automation and I'm trying to get the entities in that device so I can add/remove them from a light group. I have the node_id and device_id. I just can't figure out how to get the light in that device.
this works fine for me:
{% set id = device_id('lock.dr_door_lock') %}
{{ device_entities(id) }}
Hello, I'm having troubles using namespace to create a list from strings. Please see http://pastie.org/p/2b3EzAWTqCfvUJhccdUkHJ for detailed information, thanks
You need to turn the new item into a one item list by surrounding it with []
{% set ns.items = ns.items + ['new_thing'] %}
Yah I just figured that from searching from one of your examples in the past....Bit rusty. thanks though, thanks twice!