#templates-archived
1 messages · Page 104 of 1
@topaz silo post your sensor .share
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
don't paste into discord, use one of the services i linked
{% if is_state('sensor.goodwe_battery_mode', '3') %}
or states.sensor.goodwe_battery_mode.state but is_state is better
oh, i need to add .state (or use is_state)
@small wolf maybe by using a statistics sensor? you choose a max_age of, let's say, 30 seconds, then you will be able, in another sensor, to compute (max_value - min_value) / 30 ?
im dumb anyone get any idea as to why im dumb;
basically want a push button when i hold it down it sends the code, ON (....2445) then on release of the button it sends, OFF (...0695)
http://puu.sh/GxwFK/edd3115578.png
binary_sensor:
- platform: template
name: "ir curl"
on_state:
rest_command:
method: GET
url: http://10.0.0.92/ir?code=16712445
then:
rest_command:
method: GET
url: http://10.0.0.92/ir?code=16750695
Indentation?
im trying to template timestamp to this data format but im struggling with miniseconds: 2020-09-19T08:18:47.096Z
%f makes microseconds (.00000) but how can i make milliseconds?
{{ utcnow().timestamp() | timestamp_custom("%Y-%m-%dT%H:%M:%S.%f") }}
in Python i would just add [:-3] at the end
{% set a= "2020-09-19T12:01:25.000000" %} {{a[0:-3]}} will produce 2020-09-19T12:01:25.000
@jagged iron , I don't understand what you are trying to do. If you want to trigger rest call when a button is pushed or release, you should do it in an automation
by the way, as Tyler Marrs sayd, your indentation is wrong, and I don't know what are these tag on_state and then that you are using
@deft timber thanks
{{ (utcnow().timestamp() | timestamp_custom("%Y-%m-%dT%H:%M:%S.%f"))[0:-3] ~ "Z" }} works
@deft timber
following this: https://esphome.io/components/binary_sensor/index.html#binary-sensor-on-state well trying to anyway
so i want a button on the dashboard the will "curl" a url when pushed/held down then on release it will send the second url if that makes more sense or not
on_state
"This automation will be triggered when a new state is received (and thus combines on_press and on_release into one trigger). The new state will be given as the variable x as a boolean and can be used in lambdas.
"
@jagged iron you need an automation for that, you cannot do a binary_sensor which actions something like sending a code
ok, this is an esp. Your "on_state" should be indented on the same level as platform
yeah sorry its and ESP
@elder moon thanks will try
not send rather just call it, there no POST or GET needed it just needs to be access or called then it executes on the device thats being called
@jagged iron ah dont mind me, i thought youre talking about Home Assistant
im not sure if i am not either :D!
total noob to this
perhaps i should clarify , i am using home-assitant is which has the esphome "plugin" installed and im trying to program the esp to do curl commands for, which now that i typed it out sounds dumb....
i should be using home assitant to do for me and not getting another mcu to do it
is that possible?
one more question regarding templates - is it possible to remove starting/trailing whitespaces, something like strip() in python
@jagged iron im not really sure what exactly you want to do, i dont have any ESPs, but the general principle is that HA is getting data from other sources (like your ESPs) and runs automations based on that data
you're looking at ESP documentation, which suggests that you want to do something ON the ESP, in this case people here wont be able to help as this is Home Assistant discord
if you want to do an automation on Home Assistant though, then you're following documentation for a wrong software 🙂
Firstly set up integration with your ESPHome in Home Assistant https://www.home-assistant.io/integrations/esphome/
im assuming that after you done with that you will have your buttons state exposed to HA
like a binary_sensor created out of it
and then you can create a really simple automation within HA, triggered by your binary_sensor going on, sending data you need, waiting for binary_sensor going off, sending some more data
@elder moon , concerning your question related to the 'strip()', for that you should replace the {% and %} by {%- and -%}
or just use .strip() in your template. By default all templates strip whitespace accept for templates in markdown cards or notification service calls.
{{ ' dlsajdflak '.strip() }}
returns 'dlsajdflak'
Thanks all
Unfortunately I found out that I don't need to template this as Restful sensor platform doesn't accept templates for headers anyway:(
it doesn't remove the newlines and crap added by the template itself that's what the - are for
After an upgrade from 114 to the latest 115 many of my template sensors (mainly temperature calibration) are now saying unknown?
Seems to calculate right on template developer tool
However if I click the sensor the graph shows the correct value. Lovelace problem?
Reloading template entities (new entry in server controls) seems to correct it
i'm getting an analog value from tasmota rain sensor. It goes from 1024(dry) to 0 or near 0 with heavy rain. How i transform that value in a 0/100% being 0% the analog 1024 and 100% the analog 0?
when using a value_template for json its value_json. What do I use if it isn't json? just value ?
should work
oh boy
value_template: "{{value * 100}}"
so if value is a string, you get a string consisting of 100x 1
apart from that it works. thx
@woven folio creating a simple percentage is rather trivial with a template, but it looks like you want to invert the percentage and that would be a pita
would need to find a formula to do what you want
@woven folio The compensation integration would translate values using a linear fit, but I haven't finished writing it. For now, you'd have to use this equation: "{{ -0.0494071146245059 * value + 100 }}" in a template sensor.
sensor:
- platform: template
sensors:
heavy_rain_percent:
friendly_name: Rain Percentage
value_template: >
{% set value = states('sensor.tasmota_rain_sensor') | float %}
{{ -0.0494071146245059 * value + 100 }}
Hey, I have a problem with my RGBW light. When I say Google to "change the light to white", it doesn't change to the white channel, it changes to some RGB values (and the RGB LEDs are lower watts than the white LED, so it's really dimm and not nice at all). I found a workaround via automation. It listens if any of the light turns to that exact RGB values that Google changes the light to, and then changes to the scene with white channel. My problem is that I would like to change only the light I am saying to the google. Now it changes to the scene, which is not optimal. Is there any line of code that would change only the light that got those "white" RGB values? https://paste.ubuntu.com/p/ztyqrbrqS4/ (it uses the scene now in the "actions") I am sorry I am a big noob with codes. Thanks for any help ❤️
I have a template question: I have a rest_command , with payload with a {{state}} variable. now I want to set state via service_variable as {{ states('switch.e) }}.
This does not work, I get OrderedDict([('[object Object]', None)]) in there
@robust lodge Is it because you’re missing a quotation mark? Or was that a typo into Discord?
typo in discord
This problem has been quite a frustrating one. HASS is running under OS X via virtualenv and I need to execute minidsp mute enable as a shell command, where minidsp is a Node.js utility.
switch:
- platform: command_line
switches:
workstation_screens:
command_on: "/usr/bin/caffeinate -u -t 2"
command_off: "/usr/bin/pmset displaysleepnow"
friendly_name: Screen
dirac_minidsp:
command_on: '/Users/haru-tan/.nvm/versions/node/v10.7.0/bin/node "/Users/haru-tan/.nvm/versions/node/v10.7.0/lib/node_modules/minidsp/minidsp.js mute enable"'
I have provided complete paths to all elements, yet it returns a "command failed" error.
Executing node and minidsp alone is successful but upon adding the arguments for the latter, it fails.
Perhaps I have overlooked a syntax error but making changes to it has been unsuccessful, thus far.
did you try removing the quotes around the argument?
Yes. I also tried inverting the quote forms.
you may be better of making a shell script that just does that for you. I had some issues with a shell_command and doing that helped
put the commands/logic in the shell script and just worry about calling that
that way, you can test the shell script independently and add debug to try to figure out what's wrong
I would expect a script to behave effectively as a proxy to the direct command.
just throwing stuff out there based on my experience
I will certainly give it a try, however.
HASS should really make use of the PATH variables. It would simplify much of this.
most installs of HA are not in the system path at all
Granted, this is a relatively niche installation type.
and using full paths eliminates any ambiguity about what you're doing
It would still be handy to have the option.
but that's also where creating a shell script helps - you can make it do whatever you want
Anywho, let's see if this works.
pull in your environment, set the path, etc.
#!/bin/sh
minidsp="/Users/haru-tan/.nvm/versions/node/v10.7.0/lib/node_modules/minidsp.js"
node="/Users/haru-tan/.nvm/versions/node/v10.7.0/bin/node"
node minidsp mute enable
This still fails.
hmm if I click edit as yaml it shows: '[object Object]': null
Ah. There may be a path issue with that one. Hold on.
Path issue corrected but it still fails. It works when run in the terminal.
$node and $minidsp
Yes, caught that.
Got it. After fiddling the with script permissions, it is working.
Thank you for that suggestion, @inner mesa.
I am trying to make an automation that, if any light changes to a specific RGB value, it will set the white_value of that one light to 100% (255) What am I doing wrong? (I have no idea what I am doing)
@craggy schooner posted a code wall, it is moved here --> https://paste.ubuntu.com/p/dkYZvZP76M/
Basically what I want to achieve is this: If any of the RGBW lights receives the RGB value of 255,221,172, turn that light's white_value to 255 (or 100%).
Also now I noticed that in the code I sent here, I left the RGB value of pink or some weird color just to test if it works. normally there would be white_value or how it is properly written.
well, not a comment per se on the template, but your trigger will fire the automation every single time any entity at all changes state. and you have it set to mode 'single'
the odds that the one it would catch happens to be the light is extremely unlikely
maybe the condition would fix that but idk
@craggy schooner
i would try running it as parallel instead
or use a different trigger
I see that in the Templating docs it mentions "Process incoming data from sources that provide raw data, like MQTT". Is there any way I can change my value template from something like: "{{ states('sensor.player_songtitle') }}" to where it just reads from the MQTT topic without needing to make a sensor for it? my topic is musicplayer/songtitle
this is for an automation @hardy iris ?
no, its for a custom component im working on. I just need to read that topic and feed it into my component
so I'm seeing if theres a way to template this without having to need a sensor be made
oh i see. ive never made a custom component but with an automation I'd use an mqtt trigger and just use {{ trigger.payload }} or something to pull the song title
Ill look into it more, it was a bit hard wording this on google and finding the right results
@hardy iris no unless you go custom
Alright, thanks for the help guys!
@violet oyster sorry that was an automation that my friend made, I have no idea what I am doing. https://paste.ubuntu.com/p/ztyqrbrqS4/ This is the template that works for lights, only thing that I don't have is the action, I need it to set only that light that changed to that specific RGB color, not any other. Is there a way to do it?
@craggy schooner I am sure one of the guru's would have a much better way of handling your situation but you could create a template sensor that outputs the light entity's name as a state depending on if values where you would check the rgb of each light then use that sensor as a trigger for the automation as well as the trigger.to.state in the action template.
@mighty ledge thanks, i'll give it a try
Can I somehow show the name of the user in lovelace as a template? Like Hello {{username}}
@tidal heart https://www.home-assistant.io/lovelace/markdown/
@lofty arrow Thanks!
Is it possible to make a graph?(or something better?) of the attribute "raw_today" from this sensor?: https://paste.ubuntu.com/p/3HM8XHY3JC/ i try with {{ state_attr('sensor.nordpool', 'raw_today') }} and that gives me this looong line: https://paste.ubuntu.com/p/j68KVD5fK4/ I guess i need to add something to the template? Can someone help me? 😄 if this is possible..
Can I combine these two switch on/off automations into one? https://paste.ubuntu.com/p/b48wbvjd89/
Yes you chould, by using a choose in the action part
(is_state('binary_sensor.morning', 'on') and is_state('sun.sun', 'below_horizon') and is_state('binary_sensor.someone_home', 'on')) or is_state('binary_sensor.morning', 'off')
and in the choose, if binary_sensor.morning is on, turn off, otherwise turn on.
Maybe you could also use a template to define the service instead
action: service: {{ "switch.turn_off" if is_state('binary_sensor.morning', 'off') else "switch.turn_on" }}
cool, totally forgot about that new choose option. Guess I should have posted in automations. Thanks
action: service: switch.turn_{{states('binary_sensor.morning')}}
to make it shorter
Since upgrading to 0.115 some (but not all) of my time sensitive sensor templates have given a result as "Unknown". I have updated them so that all entity_id's have been removed, and I have added the trigger line "{% set sensor_trigger = states('sensor.time') %}" to get the sensor.time to work. The templates give the expected correct result when I put them in Developer Tools/Template. The template is at https://paste.ubuntu.com/p/yBVcWWckKX/
Thank you for your advice.
@oak mason are any of the referenced sensors template entities themselves?
@violet oyster thank you very much for your reply. Yes, sensor.pool_heat_multiplier is a template entity. The template is at https://paste.ubuntu.com/p/8CvssYkK8j/
did you use the new template reload feature recently?
there is an open issue about this https://github.com/home-assistant/core/issues/40611
for me, they work again if I restart HA
Yes I have used that. I have used it again now and I now have an "Entity not available" showing on the web page. From memory this reverts to the "Unknown" when I reload HA. I will take a look at your link. Thanks again for your help.
I am back to the sensor showing "Unknown" again after restarting HA.
But it is definitely something to do with the template entity "sensor.pool_heat_multiplier". When I replaced it with a number the master template worked as expected ie gave a correct output.
interesting. wonder why
@oak mason is the pool_heat_multiplier showing unknown also?
@violet oyster Sorry for the delay. The pool_heat_multiplier shows the correct output.
which one is defined first in the config.yaml?
Hi @dreamy sinew, calc_pool_pump_active comes first and pool_heat_multiplier comes lower down the page.
Does that make a difference?
yep, flip the order
I'm on it
referencing something that doesn't exist
You're a champion @dreamy sinew, problem solved! I wonder why it has become an issue only since 0.115. Is it because when the entity_id was being used all the referencing was being done before the calculating?
i'm not sure. they definitely changed how things are initialized but i haven't dug in to what actually changed
Rock and roll, thanks very much for your help!
i want to trigger alexa routine from home assistant
what i can do to do it
the only method is the binary sensor but I don't know how to configure it
I tried this:
-binary_sensor:
- platform: template
sensors:
alex_a:
friendly_name: alexat
value_template: ->
if ('input_boolean.alexas', 'on')|float > 0 }}
{{ is_state('input_boolean.alexas', 'on') }}
yeah, what you wrote isn't a template
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
yeah, what you wrote isn't a template
@dreamy sinew now I have to past that in configuration.yaml and everythings is ok?
Should work but you should verify in the template tester
Should work but you should verify in the template tester
@dreamy sinew tester? 😅
developer tools > template
hi all. let per say I got this sensor showing 13:47:06 up 3 days, 22:24, load average: 1.45, 1.58, 1.40 and would like to used only up 3 days 22 and 24 is this possible? anyone can help me out?
@clear pulsar Here's something to get you started ```yaml
{% set value="13:47:06 up 3 days, 22:24, load average: 1.45, 1.58, 1.40" %}
{{ value.split(" ",1) }}
{{ value.split(" ",1)[1] }}
{{ value.split(" ",1)[1].split(",") }}
{{ value.split(" ",1)[1].split(",")[0] }}
got it.. thanks @charred dagger
yes.. thanks for @wise arrow and @charred dagger ya all been great.. it working now
now got my synology uptime
You can also use regexp. The following will only select what you want and put it in a table:
{{ (value | regex_replace("[^ ]* ([^,]*), ([0-9]*):([0-9]*).*$", "\\1,\\2,\\3")).split(",")}}
Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have two problems.
🙂
alas.. still have work to do hahahaha... if it only show minute its saya 10 min
arrgggghhhh
rather then showing 10:30
Maybe you should try uptime -p?
{{ (value | regex_replace("^.*(up .*)days?, ([0-9]*):([0-9]*).*$", "\\1days,\\2,\\3")).split(",") if value|regex_match("^.*day.*$") else (value | regex_replace("^.*up ([0-9]*) min.*$", "up 0 days,0,\\1") ).split(",")}}
should work
Maybe you should try
uptime -p?
@charred dagger you are correct I should used that command instead just uptime. Arrrgggghh after I complete the what I need too hahahaha... Again thank you soo much
Im trying to make a graph of future values, can anyone smarter than med see what is wrong? : https://paste.ubuntu.com/p/jXv9bJMjxY/
What's happening and what isn't?
And alsoyaml {% if now().hour < 12 %} {{ state_attr('sensor.nordpool', 'today')[now().hour + 12] }} {% else %} {{ state_attr('sensor.nordpool', 'tomorrow')[now().hour - 12] }} {% endif %}
@charred dagger
Tack för svar! I want to make a graph for future electricity prices from these attributes. https://paste.ubuntu.com/p/tcWfsgkSmq/. Is it better to use raw_today as they contain date and time maybe? Testar jag det du skrev får jag ett värde rätt bara 😛 för svårt för mig.. hehe
so i updated to 0.115.5 ...can anyone tell me why this does not work ...
- platform: template
sensors:
ds_avg_temp:
friendly_name: "Downstairs Average Temperature"
unit_of_measurement: "°F"
device_class: temperature
value_template: >-
{{ ((float(states.sensor.downstairs_temperature.state) + float(states.sensor.living_room_temperature.state) + float(states.sensor.entryway_temperature.state) + float(states.sensor.office_temperature.state) + float(states.sensor.front_entry_fibaro_multisensor_temperature.state)) / 5) | round(1) | default('unknown') }}
...but this does?:
- platform: template
sensors:
us_avg_temp:
friendly_name: "Upstairs Average Temperature"
unit_of_measurement: "°F"
device_class: temperature
value_template: >-
{{ ((float(states.sensor.upstairs_temperature.state) + float(states.sensor.nursery_temperature.state) + float(states.sensor.guest_room_temperature.state)) / 3) | round(1) }}
both worked fine until now.
how does it "not work"?
ah sorry - more specifically, all those values still show numeric results individually and collectively with:
{{ ((float(states.sensor.downstairs_temperature.state) + float(states.sensor.living_room_temperature.state) + float(states.sensor.entryway_temperature.state) + float(states.sensor.office_temperature.state) + float(states.sensor.front_entry_fibaro_multisensor_temperature.state)) / 5) | round(1) | default('unknown') }}
in developer tools.
However, in my frontend, and in the sensor for value sensor.ds_avg_temp shows unknown
driving me crazy! lol
what does the whole thing show in
-> Templates?
normally it is due to one of the sensors being offline, obviously but they are all giving me values...
you should use states('xxx') rather than what you're doing
that helps in exactly this situation
and...less typing
it shows this:
sensor:
- platform: template
sensors:
ds_avg_temp:
friendly_name: "Downstairs Average Temperature"
unit_of_measurement: "°F"
device_class: temperature
value_template: >-
78.7
works!
wait what? explain `states('xxx') please
ok. I just meant the template part, but that's good
replace states.sensor.front_entry_fibaro_multisensor_temperature.state with states('sensor.front_entry_fibaro_multisensor_temperature') and so on
I think i ran into issues that way if im following ...this gave me results so i went with it lol
ah I'll give that another try...ever see it work in the evaluator but not at the sensor?
no
see the warning in this section: https://www.home-assistant.io/docs/configuration/templating/#states
ah - ok thanks, I'll give this a try and clean up the code maybe too.
shit, I've seen that before too - I thought I went thru my templates at the time 🙂
Also, is the sensor that isn't working depending on another template sensor?
no, they are all ecobee except for the fibaro
Unless you're using the Homekit Controller, Ecobee sensors aren't terribly reliable
that's actually a pretty great page. I don't think I've gone through it before
I probably point people to it more than I actually spend time there myself
I'm just getting unknown, not sure why
name: “Upstairs HVAC Lineset Vapor”
state_topic: “tele/tasmota_6839FD/SENSOR”
availability_topic: "tele/tasmota_6839FD/LWT"
payload_available: "Online"
payload_not_available: "Offline"
device_class: temperature
unit_of_measurement: ‘°C’
value_template: >-
{%- set sourceid = '3C01B5562F1C' -%}
{%- for tsensor in value_json -%}
{%- if value_json[tsensor].Id == sourceid -%} {{value_json[tsensor].Temperature}}
{%- endif -%}
{%- endfor %}
tele/tasmota_6839FD/SENSOR = {"Time":"2020-10-01T23:00:34","DS18B20-1":{"Id":"3C01B5561C7F","Temperature":17.6},"DS18B20-2":{"Id":"3C01B5562966","Temperature":18.3},"DS18B20-3":{"Id":"3C01B5562F1C","Temperature":21.9},"DS18B20-4":{"Id":"3C01B5567958","Temperature":23.6},"DS18B20-5":{"Id":"3C01B5568B3A","Temperature":9.3},"TempUnit":"C"}
So the block at the bottom is the data?
yes
Value_json is not a list
but as the sensors could go missing, be replaced, ...
I need to match it via id and not name
I'm not sure what not a lost, means
Not a list
ok
You can't iterate that way
No, your logic is wrong
na, my logic is from a json background, but not python
You can't iterate over an object that way in jinja2
ya this python makes no sense to me 😦
{%- set sourceid = '3C01B5562F1C' -%}
{% for value in value_json.values() if value.Id == sourceid %}
{{ value.Temperature }}
{% endfor %}```
you can't iterate over an object directly
that works in the template tester
I made a typo, retesting
oh and to be clear, you don't need that set value_json in yours
i just needed it to test since i don't have your data
ya, I didn[t put that
its not completely obvious so i wanted to be sure
still not
name: “Upstairs HVAC Lineset Vapor”
state_topic: “tele/tasmota_6839FD/SENSOR”
availability_topic: "tele/tasmota_6839FD/LWT"
payload_available: "Online"
payload_not_available: "Offline"
device_class: temperature
unit_of_measurement: ‘°C’
value_template: >-
{%- set sourceid = '3C01B5562F1C' -%}
{% for value in value_json.values() if value.Id == sourceid %}
{{value.Temperature}}
{%- endfor %}
oh wait, value is a thing already. change value to anything else
for v in ... if v.Id... v.Temperature
still nothing 😦
{%- set sourceid = '3C01B5562F1C' -%}
{% for item in value_json.values() if item.Id == sourceid %}
{{item.Temperature}}
{% endfor %}
hmm, not sure then. its a valid template
you have a bunch of fancy quotes in your yaml there, might not be helping
works fine in template editor too here
thats almost got it
ah, that sensor that isn't worked dropped offline
reason why matching them via id and not name
haha
wow
2 bme280's
just need to add two pressure sensors, and some relays and should be finished up
but wanted to run awhile with just the tempature sensors so I can do the calculations
used to do HVAC work, this will give me full complete calibaration of the unit on each cycle
noice
can adjust fan speeds, notify if filters need changed
coil freezing, refrigerant leak, or a ton of other self diagnostics
must have a bad crimp on the jst for that sensor
guys... need more advice..
I need to get uptime from 2nd synology
to do that I will need to used SSH command
however from HA command its keep showing fail
any idea how to do that?
2nd synology dont have HA running
when calling ssh from HA you need to make sure that you are using the full path of ssh binary, and the the user used to run HA can connect to ssh without prompting for a password
you could also use SNMP instead of ssh, but it requires more setup
I have a template sensor which has broken in the latest version, but the template string still works in the dev tools. Any ideas? {{(((states("sensor.electricity_wholesale_estimate")|float) + (states("input_number.electricity_supply_charge")|float))*state_attr("sensor.electricity_usage_statistics","change_rate")*3.6*1.1)|round()}}
hello guys, can you help me with this template. I have this one :
- platform: template
nodemcu_ds18b20_bme280_temperature:
entitiy: sensor.nodemcu_ds18b20_bme280_temperature
friendly_name: 'Huidige opbrengst'
value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('unknown','0') }}"
in my sensor.yaml
but when i did check I have error:
root@plex-server:~# ha core check
Error: Testing configuration at /config
INFO:homeassistant.util.package:Attempting install of httplib2==0.10.3
Failed config
sensor.template:
- Invalid config for [sensor.template]: [nodemcu_ds18b20_bme280_temperature] is an invalid option for [sensor.template]. Check: sensor.template->nodemcu_ds18b20_bme280_temperature. (See ?, line ?).
your line nodemcu_ds18b20_bme280_temperature:should not be there
it should be
- platform: template name: nodemcu_ds18b20_bme280_temperature entitiy: sensor.nodemcu_ds18b20_bme280_temperature friendly_name: 'Huidige opbrengst' value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('unknown','0') }}"
same result
ha core check
Error: Testing configuration at /config
INFO:homeassistant.util.package:Attempting install of httplib2==0.10.3
Failed config
sensor.template:
- Invalid config for [sensor.template]: [name] is an invalid option for [sensor.template]. Check: sensor.template->name. (See ?, line ?).
are you sure about the indentation of your configuration file? everything should be aligned in the sensor config
yes, it is in separate file sensors.yaml
- platform: template
name: nodemcu_ds18b20_bme280_temperature
entitiy: sensor.nodemcu_ds18b20_bme280_temperature
friendly_name: 'Huidige opbrengst'
value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}"
for example other sensors, which are described here with other platforms work fine
according to this page https://www.home-assistant.io/integrations/template/, it should be
`sensor:
- platform: template
sensors:
nodemcu_ds18b20_bme280_temperature:
friendly_name: "Huidige opbrengst"
value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}"`
[name] is an invalid option for [sensor.template].
sensors: by my opinion have not to be there. It is already in separate file sensors.yaml
which is described in configuration.yaml
yes indeed, that was a generic answer 🙂
- platform: template
name: nodemcu_ds18b20_bme280_temperature
entitiy: sensor.nodemcu_ds18b20_bme280_temperature
friendly_name: 'Huidige opbrengst'
value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}"
@keen sky you should remove name: in line 2
and as your friendly name is the same as the name (besides the senor. part), it's not needed to specify it
I remove it and frendly_name as well
- platform: template
nodemcu_ds18b20_bme280_temperature:
value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}"
Error: Testing configuration at /config
INFO:homeassistant.util.package:Attempting install of httplib2==0.10.3
Failed config
sensor.template:
- Invalid config for [sensor.template]: [nodemcu_ds18b20_bme280_temperature] is an invalid option for [sensor.template]. Check: sensor.template->nodemcu_ds18b20_bme280_temperature. (See ?, line ?).
- platform: template
nodemcu_ds18b20_bme280_temperature: None
value_template: {{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}
what mean this ? INFO:homeassistant.util.package:Attempting install of httplib2==0.10.3
did i miss to install something ?
did you try what I proposed here #templates-archived message topche?
yes
hmmmmm
i put sensors: and it is work now ....
hmmmm
even it is at seprate file snesors.yaml
Yes, that is why the first sensor: is not needed
But after that you define (within sensor.yaml) that you want to use the template plaform
And in this template platform, you can the define multiple sensors, that is why that sensors: is needed
So you could multiple template sensors under that one - platform: template line
*could create
now i replace it in my gauge card with new entity : sensor.nodemcu_ds18b20_bme280_temperature_2
but still have some picture
fixed 🙂
thank you guys !
just remove value_template: {{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}
i have additional question. I have a lot of sensors as this one. Have i do templates for each one ? Or have more intelligent way to do for all of them ?
Hi ! I have created a scrape sensor that checks if there is a new FW for my router. It works. Now I would like to create a binary sensor that shows me if the value of my scrape sensor changed. All the examples that I found are using a template binary sensor, but all of them rely on a threshold with which you need to compare your value. In my case, I don't have a threshold. I would just need the binary sensor to be triggered when the FW sensor changes after a while (1 day, for example). Any suggestions ?
I'd say 1 template sensor for each
Hi all, I have 4 sensor entities to get ink levels and a 5th to get status of my printer. When my printer is on, I have the ink levels like this :
https://ibb.co/LtbQxpD
When my printer is off :
https://ibb.co/9TDPHc4
I'd like to get the last ink levels with normal color drop icon when printer is off
and the update ink levels with personalised ink color (black, yellow, magenta, cyan) drop icon when printer is on
I looked around templates and icon_color with custom UI but without success
Thanks for you help
@thorny snow you should create 4 template sensor with a condition if is not unknown return value...
Hi can anyone help me with the shelly em config in homeassistant? when i use value_template: "{{ value_json.ENERGY.Power }}" the result is [0,449] how to i remove the []?
@summer ore i have create a input_text which get the fw version when i check a button card.. And a automation which compare sensor.fw_version and input_text.current_version
@thorny snow So you have to fill in the current version every time ?
@dreamy sinew no i just want the 449 part
is it always 2 values?
@summer ore yes because i update every first weekend but the automation can update input_text with service
i dont mind if its 0,449 i can multiply it by 1000 to get 449 i just need to remove the square brackets
that is a list of 2 numbers, so please answer the question. Are there always 2 items in that list?
oh ok yes the shelly em has 2 clamps but im not using the other one so if its a list then yes i only want the 449 part the 0 will allways be 0
i didnt know the comma was a list
{{ value_json.ENERGY.Power[-1] }}
i will try that thank you.
just out of curiosity how would i get the first number?
[0]
ok and if i wanted the middel value of 5 options i could use [2]
i get it
thanks
yep, 0 index
i see
- starts from the end
I just rebooted and that works perfectly thank you.
and thanks for the rest of the information
is there any way to extract information about persistent notifications?
for example, I would like to get a push notification on my phone whenever something generates a persistent notification
not that i've seen
the only thing I have found is I can do:
{{ states.persistent_notification | length }}
I wonder if there’s an event
which will let me now that something happened... just can't get info about it
@inner mesa good idea
there is: persistent_notifications_updated
which gives:
Event 0 fired 10:08 AM:
{
"event_type": "persistent_notifications_updated",
"data": {},
"origin": "LOCAL",
"time_fired": "2020-10-02T17:08:53.852771+00:00",
"context": {
"id": "f31f603904d111ebbff64fdec341da28",
"parent_id": null,
"user_id": null
}
}
doesn't seem to have any of the data of the notification though (title, message, etc)
still having trouble with this after updating
sensors:
last_motion:
friendly_name: 'Last Motion'
icon_template: 'mdi:motion-sensor'
value_template: >
{%- set pirs = [states.binary_sensor.kitchen_motion_sensor, states.binary_sensor.master_bedroom_motion_sensor, states.binary_sensor.master_closet_motion_sensor, states.binary_sensor.living_area_motion_sensor, states.binary_sensor.full_bath_motion_sensor, states.binary_sensor.half_bath_motion_sensor, states.binary_sensor.stairs_motion_sensor, states.binary_sensor.kids_room_motion_sensor, states.binary_sensor.play_room_motion_sensor] %}
{% for pir in pirs %}
{% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
{{ pir.name }}
{% endif %}
{% endfor %}```
@brave root When I call the actual service, I get this:
I don't know if "internal" ones follow the same path, but that has the content
what event were you listening for?
right, I guess I could try to filter all call_service events, but you're right, does the 'house' use some internal thing
you could add garbage to your automations.yaml and reload automations. that will create a persistent notification
hmm, doesn't fire
hello people, can I ask for your help. I just start to learn how to make templates and have not idea at all about the logic. However, i have this {{ nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }} and obviously this always replace with 0. This sensor is online not all the time and I want when it is online to read the data from nodemcu_ds18b20_bme280_temperature, but when is offline to display 0 or even better to display "Not available"
or if you can point me some link to read about the "program language" for templates will be best
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
anyone willing to help, feel free to @ me so ill get a notification.
why % is at the beginning like {% if state.sensor.nodemcu_ds18b20_bme280_temperature ......%}
It’s part of the template syntax
Jinja Template Designer Documentation
For more examples and samples, visit see this page
actually let me ask if i take correct way. I have card for one sensor, which is not all the time online. I want , when is it to display the data, when is off to display something like "Not online"
so have i use templates for that ?
and really which program language use templates ?
it's "jinja", as above
okay .. very exotic for me 🙂
if you're not happy with the sensor state text when it's available and when it's not, you can either create a template sensor to customize the state names, or you can use a card that lets you add a template right in the Lovelace config
it's generally Python-like
RobC you able to help me if you have time?
Hey I have custom template sensor state with a list of entities comma separated which needs to be turned off, how to provide the entities list for the turn off action?
- platform: template
sensors:
wz_tv:
friendly_name: WZ TV
value_template: >
{% if is_state_('binary_sensor.wz_fire_tv', 'on')
or is_state('media_player.ps4', 'playing') %}
active
{% else %}
inactive
{% endif %}
what is wrong with this template over here? the sensor shows as unavailable
improper indentation?
its looking fine for me, but iam not sure
is_state_('binary_sensor.wz_fire_tv', 'on')
^
oh 😫 copy and pasting fault. Thanks for your help that should do it
Hello, is it possible to get the last state of a cover in its own value template?
I try somethings like this:
{% if is_state('binary_sensor.garage_open', 'on') and is_state('binary_sensor.garage_closed', 'off') %}
open
{% elif is_state('binary_sensor.garage_open', 'off') and is_state('binary_sensor.garage_closed', 'on') %}
closed
{% elif is_state('binary_sensor.garage_open', 'off') and is_state('binary_sensor.garage_closed', 'off') and is_state('**xyz last state of this cover **xyz', 'closed') }} %}
opening
{% elif is_state('binary_sensor.garage_open', 'off') and is_state('binary_sensor.garage_closed', 'on') and is_state('**xyz last state of this cover **xyz', 'open') }} %}
closing
{% endif %}
how do I negate is_state_attr?
With ‘not’
hi everyone I used variable to create yesterday info, however need to ada info on the numbers. Try to used ```
- platform: template
sensor:
worldwide_coronavirus_new_today_dot_separated:
friendly_name: New cases in the World Today
value_template: "{{ '{:,}'.format(states.variable.worldwide_coronavirus_new_today.state | int).replace(',','.') }}"
unit_of_measurement: ""
I got error..
is there away to show variable.worldwide_coronavirus_new_today with dot seperated?
@dreamy sinew well it's been working good after all that annoyance the other day
Wow. I wanted to fix an automation that was firing at startup because a trigger state doesn't populate immediately. Wasn't expecting it to stop the error in the logs, but it did that too :D
not ((states('sensor.homeassistant_uptime') | int) < 5 and is_state_attr('sensor.homeassistant_uptime','unit_of_measurement','minutes'))
Is the second part necessary? I'm not sure if it'll change to 'hour' after 60 minutes, haven't waited long enough 😛
hi
I have an issue with my template covers
I have multiple RF covers in my home
They're all controlled using BroadLink RM Pro
I've set up a template cover for each one of the covers
With each having a scripts for OPEN / CLOSE / PAUSE .
My problem is when I restart HA , The covers default to OPEN
and not the pervious state before restart
Any ideas on how to fix that ?
~share one
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
You should check out the value_template
https://paste.ubuntu.com/p/BB98FVpczf/
That's my cover setup
I'm new to templating
so I don't really know what to do
But I figured the problem might be because the covers have no reference / or sensor that tells them the current state of the blinds/curtains so they just default to OPEN
Right, you have no value_template at all, so there’s no indication of current state
It should just default to what it was (optimistic mode)
But they're RF controlled no sensors (:
I've been thinking of maybe creating a sensor that is "last_state" for each cover and set that to the value template
But I don't really know how to do that
An input_boolean would do it
isn't there a way to do it with a sensor
Input Booleans aren't that appealing lol
can you show me an example please (:
you would use the bool to reserve the state upon restart,m you wouldn't ever see the bool
You can solve it however you like
well I got the gist of it so i'll try to figure it out
Thanks for the help (:
@thin cedar posted a code wall, it is moved here --> https://paste.ubuntu.com/p/hWQdc36jYX/
Hey guys, I've just started playing around with templates and i'm running into a problem. when i have this template as a part of my script, i can reload scripts without getting a notification. But it hangs on the spinning wheel when i try to validate config. Any ideas what might be wrong?
This is my script: https://paste.ubuntu.com/p/hWQdc36jYX/
I don’t think that’s what you want to do
You should use ‘is_state_attr’ to test ‘current_activity’ against your Apple TV activity
There’s no attribute called "Watch Apple TV", and the expression doesn’t result in a boolean true/false
@thin cedar
Thanks @inner mesa !
that explains a lot. i gotta do some more reading in how templates work "Watch Apple TV" . is what the activity in Harmony is called. i want the condition to be that that activity is currently active.
Right, I have several of those. Test ‘current_activity’
Thanks!
Like this? https://paste.ubuntu.com/p/K5YSct9sfc/ it's still giving me the same problem
@inner mesa
Yes, like that
Thanks @hoary aspen !
for some weird reason It still freezes my config validation though. i'll keep trying
Weird. I’ve heard a few people mention the config check never ending. If you gace a simple example, please file an issue
Want to see what issues are open (or were open and are now closed)?
- The core (backend) - for HA itself, and integrations
- The frontend (UI) - for cards and display issues
- The Supervisor
- HassOS
- The documentation
Finally, don't forget to check for any alerts
Hi, does anyone have experience with not displaying the data from the sensor template in LOVELACE, but the data is shown in the test template?
~share the template
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
OK, only the one that doesn't work is needed, I guess the third is the sensor
line 12-16
Pictures and a detailed problem is in the last post on this page. It helped?https://community.home-assistant.io/t/viessmann-component/77873/298
is that like "unknown"?
no, it's like "undetected" and in detail "status history is missing". But it appeared after the reboot. Sometimes it was just there and it worked and sometimes it didn't. But in / developer-tools / template it works and shows the current curve.
where does the sensor data come from? MQTT?
No, the data comes from the Viessmann API
are you running at least version 0.115 of HA?
0.115.6
try
-> Server Controls -> Reload Template Entities
super 🙂
better?
Thank you. Amazing, now it works like a miracle. I tried many restarts and it didn't work. But this is now happening immediately.
👍
excellent. that means that one or more of those entities wasn't available or reporting data when HA started and none of the entities changed later to cause the template to be reevaluated?
which is weird, because it seems like they clearly did change
I don't know why this is so, but it is possible that one of the code could not have changed and that is the target temperature, so it is probably always the same?
but it would probably be a good idea to adjust it somehow in some automation, so that this always plays after the restart, so that the data is then in order. Is it possible to treat it in any way?
you can call homeassistant.update_entity on that entity when you wish, or you can add something like {% set t = states('sensor.time') %} to your template to make it reevaluate regularly
I'm not so experienced to do this. Where exactly should it be in that antite to update it regularly?
but it shouldn't be necessary if the sensors are updating. If you just want to update them once at start to make sure that they start with a useful value, you can trigger on the start event: https://www.home-assistant.io/docs/automation/trigger/
OK, thank you very much for your help. I didn't expect a quick response from "our" Home Assistant community 🙂
Good morning! I'm working on a template sensor which works fine in the templating tool, but when it's present in my sensors.yaml file, the Configuration Check spins with no end. When I remove it, everything's fine. I figured I'd start here, but happy to go elsewhere too.
The template in question is to turn a numerical Air Quality Index number range into friendly English text.
posts here 30mins ago recounted something similar
I'll scroll back
~share your sensor template
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
D'oh
The rest of the indents look ok?
yes
just follow the docs: https://www.home-assistant.io/integrations/template/#multiline-example-with-an-if-test
Well, the check no longer breaks, but the sensor still doesn't show up in states.
This gets me past the other hurdle, though. Many thanks!
still looking to get help with this template that broke after the last update:
- platform: template
sensors:
last_motion:
friendly_name: 'Last Motion'
icon_template: 'mdi:motion-sensor'
value_template: >
{%- set pirs = [states.binary_sensor.kitchen_motion_sensor, states.binary_sensor.master_bedroom_motion_sensor, states.binary_sensor.master_closet_motion_sensor, states.binary_sensor.living_area_motion_sensor, states.binary_sensor.full_bath_motion_sensor, states.binary_sensor.half_bath_motion_sensor, states.binary_sensor.stairs_motion_sensor, states.binary_sensor.kids_room_motion_sensor, states.binary_sensor.play_room_motion_sensor] %}
{% for pir in pirs %}
{% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
{{ pir.name }}
{% endif %}
{% endfor %}
feel free to @ me if you can help out
have you tried manual checking the date comparison in dev tools? there could be a difference when one of them has ms while the other only has seconds
thanks for the help yeah when i check it in the tool it says: This template listens for all state changed events.
and the state of the sensor says "unknown"
Hello, i'm wanting to add an attribute template to my template sensor but when i check the config in the ui, it throws me an error, can you help me ?
next_train_from_beautiran_to_bordeaux_humanized:
friendly_name: "Prochain Départ de la gare de Beautiran"
value_template: '{{ as_timestamp(states.sensor.next_train_from_beautiran_to_bordeaux_raw.state) | timestamp_custom("%H:%M:%S") }}'
attributes_template:
delayed: >-
{% if state_attr('sensor.next_train_from_beautiran_to_bordeaux_raw','delayed') == false %}
A l'heure
{% else %}
En retard
{% endif %}
easy to miss
glad it's working
now, i need to create a new device in node red to be discovered by alexa, an ultra nightmare...
hmm, can't use templates for colors in hs_color?
want to turn on a light to a random color
the forum has examples of what you can do
hmm, so is that a no or a yes?
Hello everyone. I have a ISY994i controller running in conjunction with Home Assistant and HomeKit. I’m on 5.016 and latest Home assistant version. Most of my devices are Zwave. For the most part, the integration is working great. The problem I’m trying to figure out is how to communicate with dimming lights using 0-100 parameters vs 0-255. I can control the dimmer but 100 out of 255 shows up 100% on the ISY. I tried using input numbers but that does not translate well into HomeKit because it shows up as a switch. I tried several light templates and while I can control the on and off feature, I am unable to figure out how to scale the dimmer slider. I’m hoping that some one here has had the same issue and there is an easy fix that I’m missing. This may not be the place to ask the question and if that’s the case I apologize. If someone could point me in the right direction or help me with this I would very much appreciated. I’m new to HA and I’m not big on programming but I can figure things out with a little help.
@inner mesa gotcha, so the trick is just changing from data: to data_template:
that doesn't appear to let me set a template for transition though
no
you don't need that anymore
the point is that you cannot construct a template that returns a list because they only ever return a string. So when you need to provide a list, the best you can do is to provide each list element as a template
I've done that
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
but I did have to change to data_template
what version of HA are you using?
🤷
hmm, any idea why a template wouldn't work in transition?
just not supported I guess
Would be possible for someone to look at the template. This is related to changing dimmer values from 0-100 vs 0-255
Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
how about this one? https://pastebin.com/uw0qJ6uC
the entity_id value there gives me an error when checking config:
Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['repeat']['sequence'][0]['entity_id']. Got None.
why would it be none? that template works fine in the template tester
this doesn't work either 🤔
entity_id: "light.lr_{{ ['top', 'middle', 'bottom'] | random }}"
that looks just like this to me: https://community.home-assistant.io/t/random-entity-id-in-an-action/29476
nor this: entity_id: "states.light.lr_{{ ['top', 'middle', 'bottom'] | random }}.id"
🤬
ah, thank you 👍 that's totally working now
if the transition one worked that'd be cool
might be my bulbs?
Hi, Is it possible to get the device info to use in a template? I have a Zigbee device (ZHA) and I want to get the LQI and RSSI from there.
I think a dumb question: I have a sensor that reports a date in epoch and I want to create a new sensor that contains the same date, but formatted cleanly in %a, %b %d format. I think I need a template integration for this right?
I tried this but I think I'm doing it wrong:
template:
- sensors:
next_trash_pickup:
friendly_name: "Next Trash Pickup"
value_template: '{{ states("sensor.next_trash_pickup_raw") | int | timestamp_custom("%a, %b %d") }}'
That value_template is all one line but its just not formatting right here.
Never mind, I got it 🙂 I had it backwards. This works:
sensor:
- platform: template
sensors:
next_trash_pickup:
friendly_name: "Next Trash Pickup"
value_template: '{{ states("sensor.next_trash_pickup_raw") | int | timestamp_custom("%a, %b %d") }}'
@polar pier posted a code wall, it is moved here --> https://paste.ubuntu.com/p/HyxVcxYV4Q/
Is there any (recommended) way to make a value_template re-usable. I'm converting/translating values from one sensor using value_template (and icon_template). This works great, but I want to have it applied to many sensors, and don't want to repeat myself all over my configuration with the same template snippets. Typically it seems that YAML anchors are an option, but I don't see how it would be done in my case:
fk1:
friendly_name: "Linker Fensterflügel"
value_template: >-
{% set state = states('sensor.srh1_state') %}
{% if state == 'open' %}
Geöffnet
{% elif state == 'tilted' %}
Gekippt
{% elif state == 'closed' %}
Geschlossen
{% else %}
?
{% endif %}
Now I would like to have this template applied to many other sensors, so essentially the set state= line would be different in each case, while everything else would be the same.
hi everyone.. wondering how can I replace the entity_id with? because its depreceated
- platform: template
sensors:
#----- Count Automations
count_automations:
entity_id: sensor.date
value_template: "{{ states.automation | list | length }}"
HI!
Could someone give an idea to implement device_tracker using mqtt?
@clear pulsar there are multiple posts on the forum about this, but one common way to fix it is by doing something like this:
value_template: >
{% set date = states('sensor.date') %}
{{ states.automation | list | length }}
@clear pulsar there are multiple posts on the forum about this, but one common way to fix it is by doing something like this:
value_template: > {% set date = states('sensor.date') %} {{ states.automation | list | length }}
@buoyant pine got it.. thanks
Is it possible to set a card name dynamically using a template/sensor value?
HI!
Could someone give an idea to implement device_tracker using mqtt?
@thorny snow Did you look at Owntracks ? https://owntracks.org/booklet/guide/clients/#home-assistant
Is it possible to set a card name dynamically using a template/sensor value?
@torpid gust #frontend-archived
Hey, i got some help with this one yesterday, but still can't get it to work.
I'm trying to get home assistant to check that current activity is "Watch Apple TV" before it turns the activity off. But whenever i include the template as a condition my config check freeezes. I suspect this is just user error. can anyone help me spot the error?
https://paste.ubuntu.com/p/Q5pjS4BhWb/
Thank you,
V
How can i do something like this? {{ state_attr({{variable}}, 'gps_accuracy') }}
Drop the inner {{}}'s…
Outside the {{}}'s, is text. Inside the {{}}'s, is template (Python-ish)…
Okey but in this situation then?
{{ state_attr(alias, 'gps_accuracy') }}```
that not working
Nothing me passing wrong variable xD
Can i make this one https://pastebin.com/u0krLqx8 So it has an list of names to make the alias_for_name but not name as alias?
Instead of it creating etc ida_for_ida and so on
How can I split and get only a part of a sensor's value?..
like if I have a sensor that gives back a value of 88,-834,-34 (angle sensor)..
how can I get only the middle number?
{{ value.split(",")[1] }} @fringe leaf
ty!
Is there any (recommended) way to make a
value_templatere-usable. I'm converting/translating values from one sensor usingvalue_template(andicon_template). This works great, but I want to have it applied to many sensors, and don't want to repeat myself all over my configuration with the same template snippets. Typically it seems that YAML anchors are an option, but I don't see how it would be done in my case:
@thorny snow Does anyone have some ideas here?
Template reuse isn't really a thing @thorny snow
im not used to this syntax 😒
What's the raw data look like?
um doods output
I don't use doods
Hmm, I'd need to get to a computer to work it out
yah, this is the hard part
defining box areas for sensors so I can send notifications based on criteria
looks like I should be looking at Tinkerer https://github.com/DubhAd/Home-AssistantConfig/blob/master/scripts/camera/front_camera_interesting_things.yaml
Lol wow. Yeah, he's usually on top of things
Has anyone figured out how to scale a dimmer from 0-255 to 0-100. If I use pct. HA still passes it as a 0-255.
anyone know how to tweak this template? I need it to ONLY display when the motion sensors trigger... the issue i am having right now is it will trigger when someone walks through the house and then trigger a second time when the state of the entities its watching changes to "no motion" does that make sense? lol
sensors:
last_motion:
friendly_name: 'Last Motion'
icon_template: 'mdi:motion-sensor'
value_template: >
{%- set pirs = [ entity 1, entity 2 so on... ] %}
{% for pir in pirs %}
{% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
{{ pir.name }}
{% endif %}
{% endfor %}```
almost need some type of "filter" so that it only display the state "motion detected"
I think an automation that writes the friendly name of the last motion sensor to go to 'on' to an input text would be better here
im pretty noobish
Pretty noobish and you wrote that template?
can you elaborate? im all for doing something more efficient
heck no haha
someone shared it with me while back in this channel
State trigger with to: 'on' and a list of the motion sensors for entity_id:
The action is input_text.set_value with the value being "{{ trigger.to_state.name }}"
btw all of this to just have a glance card on my lovelace so i can see which room had motion in it last
so that automation your saying i should build would stop my template from displaying the entity when the state changes twice?
It would only trigger when one of the sensors goes to 'on'
so i have a hard time understanding most of the template. what line in the template tells the sensor to look for a "state" on the sensors its watching?
or does it just watch for "all" state changes?
It's basically triggered on every state change of that list of sensors
It updates when last_updated for any of the sensors changes
got ya, think im on the same page.
i guess i just dont understand why building an automation would fix it. Wouldnt it just now see the state "on" and then "no motion" and trigger twice?
sorry just trying to understand it lol
No
That's why I said to make the state trigger with to: 'on'
I can throw it together in a bit if you're having trouble visualizing what I mean
i am... and just trying to be polite not to wear you out haha
no worries on the time frame take your time thanks for the help thus far
Nah you're good
i have zero background in this so its all self taught and this discord that gets me places..
There's a pretty big learning curve with home assistant
been a pretty fun hobby so far!
For sure, it's very powerful
if you think of me later, fell free to PM or tag so i can find it in the flood of messages lol
Yeah no prob, I'll ping you
yeah its super powerful and I have a TON of different sensors so its been cool to collect all the date and think of different automations to build and all
@topaz walrus should be what you need: https://paste.ubuntu.com/p/xKHqpPsNtv/
create an input_text named whatever you want and change the entity ID for it in the action. also update the entity IDs in the trigger as needed
@hollow rampart not sure what you're asking for
Hello. I have an Isy994i controller. I’m running rpi with HA. All d3vices are ZWave. ISY accepts brightness on a scale of 0-100. HA uses a scale of 0-255. I was trying to write a template to scale the dimmer. I did try pct attribute which doesn’t work because it will still convert it to 0-255. I have been working on this for a week.
Sorry hope that makes sense
I don't think it is possible. What integration are you using?
Universal devices isy994
This is not something that could be handled with a template. It'll be at the integration level
I did see couple templates I tried but the entities keep fighting themselves.
Ok
Thank you
Is it possible to add custom attribute to an entity (climate) and set it to its state ?
Is there a way to pull the hvac_action state from a thermostat into a template sensor? I can pull the state of the thermostat itself through but want to pull the hvac_action state which is either idle or eco..
@stone lintel if hvac_action is an attribute of an entity you can call it's state with state_attr('whatever-the-main-entity', 'hvac_action')
Amazing, thanks!
@copper blaze you'd break the entire functionality of climate devices if you did that. Best to make a template sensor to display the altered info that you want to display.
Anyone able to help with my template to create a button to increase the temperature setpoint for a climate entity?
https://pastebin.com/pUFz7whF
It complains it wants a float for the temperature
yes because it doesn't support jinja templates https://github.com/custom-cards/button-card#javascript-templates
temperature: >
[[[ return states['climate.bathroom'].attributes.temperature + 0.5; ]]]
also, as an fyi... even if it did support jinja templates, you would have needed to wrap your whole template in quotes or use the multiline template indicator (> or | ).
Where can I find info about advanced templates? I have two entities, a date and a number, and want to get the average energy per day. (The date is the start date of the total energy draw)
Jinja Template Designer Documentation
For more examples and samples, visit see this page
but it sounds like you want something like this: https://www.home-assistant.io/integrations/history_stats/
Im using tasmota and in the JSON in my MQTT topic it stores total energy and total energy since, so all HA needs to do is do total power / days since <json date>
Thanks, I'll see what I can do, I may come back if I get stuck though 😉
you can usually find solutions on the forum for stuff like this
yea, I did a quick search but wasn't sure what keywords to find what I was looking for
So this is what I have put together so far:
# SONOFF 01 - Average daily power
- platform: template
sensors:
sonoff01_average_daily:
value_template: '{{ sensors.sonoff01_total / (as_timestamp(now()) - as_timestamp(sensors.sonoff01_total_since) ) | timestamp_custom("%j")| int }}'
entity_id: sun.sun
unit_of_measurement: 'kWh'```
But unfortunately the state is just "unavailable" and I don't know how to tell whats wrong or what to check.
For info sensors.sonoff01_total is the number of kWh and sensors.sonoff01_total_since is a timestamp
Test in
> Templates
Morning all, bit of a noob with templating but I seem to be bumbling my way through it.
Could someone explain to me what int and float are. I use them but don’t quite understand them
int == Integer. Whole numbers.
float == floating point number. Decimal number
Ah ok thanks 🙂
Do templates auto update when the values referenced change? ie I do not need to add sun.sun to my entity_id list?
If it can identify the entities, yes
The entity list is also deprecated
Most of the time it will work fine
On the template page it says it listens for state changed events for my two entities
Good
Also, I got it to work temporarily, but now it keeps saying unknown even though the template works in the dev page
any logs or something I can check?
Temporarily?
Wait now its working again... I didnt change anything except restart HA
Hmmm, I am wondering if it is only updating when the state changes and on startup it has a null state
Could be
So I need to update this sensor template once a day, as it depends on days since another value. I am using now() for that. What would be the way to get it to update once a day if entity_id is deprecated?
Thanks, wish they added a better way to do this when removing the old way :/
You really shouldn’t need to do anything
The problem is I have two values, one never changes (unless I reset it) and the other only changes when power is used. If I don't use any power the value doesn't change but the average daily power draw should be going down (since we are getting further away from the permanent date)
Adding a line to your template is pretty much equivalent to another entity_id: line, right?
Adding sun.sun isn’t ideal, either
Maybe what would be best is using an entity instead of now() that updates once a day?
not sure how I would do that though
Seems like sensor.date does that
Yup, but I do not have that unfortunately. (at least according to the developer tools states page)
I think I have to create a template for that too
Then add it
But then wont we have the same issue? It wont update automatically using now()
Oh!
The updates will be based on sensor.date, which is what you want
This is what I was missing, thank you
when I make a loop like {% for device in states.device_tracker %} - how do I get the device's mac address?
I was able to do that with the luci device tracker but not anymore with the nmap dev tracker :/
the MAC addresses get saved in known_devices though
nvm, I made my template shenanigans work with the devices ip
is it possible to add a template attribute to an existing hue light/group?
i'd like having a current_scene or last_scene on the light group
You can't add stuff to existing entities with templates
ok. i guess i can make a helper of some kind per hue light group that, when the script activates a scene by name, also save that name to that helper
Yep, that can be done
template_attributes may be efficient for that - have an sub-attribute for each light group. avoids having a ton of custom helpers
why doesn't this work? url: 192.168.1.253:8123{{ state_attr('media_player.hedwig_2', 'entity_picture') }}
Does it work in template tester?
needs http://
Yup
hmm, seems to not fill reliably anyways
not too big of a deal
how about this: i want to have a switch turn on for a total of 12hr, with equal time before sunrise and after sunset
if you can figure out a way to determine that, you can plug it in to a template
@buoyant pine getting to this late, sorry been traveling for work. Thanks for you help! I saw the automation and understand it now. I do forget, what change to the template you told me to make.
@topaz walrus no prob, what I provided will replace the template entirely
You can display the input text in your frontend instead
how can I get the date from the timestamp of a sensor and make it one day later in a template?
is it a timestamp as in the seconds from epoch or a date-time string?
timestamp
1601162500 for example.
I can use timestamp_custom('%Y-%m-%d') to convert it to a datetime I guess. But I'm still lost.
yeah, trying to work something out but not having luck atm
there's a timedelta global but it doesn't seem to be working
@dreamy sinew ok I figured out the template, and can get my desired offset, but don't think I can use a sensor value as sun offset in a trigger
hope this is the right section. how do i change clock to 24hr instead of 12hr?
0{{ timedelta(0, (12*60*60) - (as_timestamp(state_attr('sun.sun', 'next_setting')) - as_timestamp(state_attr('sun.sun', 'next_rising')))) }}
is this what you're looking for?
automation:
trigger:
platform: sun
# Possible values: sunset, sunrise
event: sunset
# Optional time offset. This example will trigger 45 minutes before sunset.
offset: "-00:45:00"
I put the leading 0 because I couldn't figure out how to get timedelta to format into a HH:MM:SS
yeah, can I use a template there?
for the offset?
yeah
I thought you wanted like 6 hours before?
how about this: i want to have a switch turn on for a total of 12hr, with equal time before sunrise and after sunset
@blazing burrow ^
currently calculated to be about 35min, but as the year goes on, it'll be longer and longer
based on light level or something? simply have a fixed offset before sunrise and after sunset is trivial
oh, I see what you're doiung
nevermind
👍
it's a weird requirement 🙂
yep lol
like an interview question or something
lmao
or homework problem 🙂
it baffles me that templates don't just work anywhere
I mean I get it
but I keep expecting them to and then not lol
they work in a lot more places now than they did a couple of releases ago
understandable
and, #hacktoberfest
👍👍
I've considered a couple things, but don't really feel I'm at "contributor" level yet in terms of HA
I do quite a bit of kodi stuff, but hacktoberfest guidelines this year changed up so it's only marked repos?
or something
After doing research for some days: Is there really no way to re-use template snippets / codes (e.g. similar to a macro) for multiple sensors, with only slight differences in between those (e.g. the name of the sensor). In my case I have a long value_template expression that is 99% equal across 20 or so sensors, only the name of the "upstream" sensor changes between all of those ...
Hey guys, any way to use data_template: when using Developer Tools > States or Services?
Seems like the YAML part forces the use of data: making it impossible to test templates
no, but theoretically templates should work there in 0.115 or newer since data_template: is no longer required
Aha I didn't know that! Thanks
Hmm cant seem to get it to work:
brightness_pct: '{{100}}'
gives:
expected float for dictionary value @ data['brightness_pct']
are you on 0.115 or newer? if so, looks like that field still doesn't accept templates
i'll have to try that out when i get home
im on 0.115.6
yeah, guess it doesn't accept templates, or at the very least it doesn't convert the template output (which is a string) to a float
Hmm guess I have to find another way, thanks for the help!
Can I make the date of a timestamp one day later in a template?
{{ as_timestamp(now()) | timestamp_local }} works but if i try to add time to that but it doesn't.
I looked there but it doesn't say anything about what I am doing.
okay, doing it that way, you some some brackets… {{ (as_timestamp(now()) + 3600) | timestamp_local }}
| is a jinja operator, and is way up in precedence…
The alternative would be {{ now() + timedelta(…) }} something, but I assume timedelta was added very recently, because I don't appear to have it.
ok that worked thanks.
timedelta was added in 0.115
I can get it working in a template but I am having trouble using it in a service call to set an input_datetime object.
I get an error that could not parse date.
~~Anyone mind looking at a template sensor for me? This used to work but when I migrated to a new Pi it has stopped. I validated the template itself in the template editor and it spits out a valid number so not sure why it isn't working in the sensor. I just get an Unknown state with nothing in the logs: https://paste.ubuntu.com/p/nyPp2Dj9KG/~~ Well it just started working again after a couple weeks of not working so 🤷♂️
Using the template sensor, previously one could just use entity_id: [] to have the sensor NOT update automatically. How could I achieve this past version 0.114?
For context: I have two 'sensors' whose data I only push via HTTP, and because of that their states are purged upon a HA restart. I work around this by defining these sensors as template sensors and pull data from a dummy variable on an ESPHome device. This worked fine until 0.115, but now, as soon as a mentioned entity changes (e.g. the aforementioned ESPHome device loses WiFi) the values are reset. Any ideas on how to fix this? :)
Should probably just use input_* entities instead
i feel like i had this right last night, but isn't working anymore 🤔
always get invalid url for dictionary value @ data['url'] from my service call
.share the full thing please
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
also images of text are rage inducing
sure
{{ 'http://192.168.1.253:8123' + state_attr('media_player.hedwig_android_tv', 'entity_picture') }}
that's my template
http://192.168.1.253:8123/api/media_player_proxy/media_player.hedwig_android_tv?token=7febba290e2a771f41b0af9cb332abf278488152f2d5ee5334bbceb26321082a&cache=1602124321.277953
and what i get from it
and where are you using it?
ideally i'll be using it for the color recognizer script here: https://community.home-assistant.io/t/change-your-rgb-lights-color-according-to-spotify-album-background/94885
but for the moment i'm just testing it in a service call
how are you testing the service call?
gui does not support templates in the dev-tools > services
well, it definitely didn't prior to 115. it might now. ¯_(ツ)_/¯
yeah, still getting that error from my automation
service: color_recognizer.turn_light_to_recognized_color
data:
entity_id: light.lr_bottom
url: '{{ states(''sensor.spotify_android_tv'') }}'
entity_id: light.lr_bottom
that's not what you were using earlier, what is the output of that sensor?
ohh, it's that:
sensor:
- platform: template
sensors:
spotify_entity_picture:
value_template: "{{ 'http://192.168.1.253:8123' + state_attr('media_player.hedwig_android_tv', 'entity_picture') }}"
friendly_name: Spotify Entity Picture
lemme use the template directly
ohh i made it further
now got an error from my script 😅
test_tts:
alias: TEST TTS
sequence:
- service: tts.google_say
data:
entity_id: media_player.alla
language: sv
message: "Prisen för elen är just nu {{states('sensor.sensor.electricity_price_angshestre_120')}}."
cache: false
I'm getting unknown for the state, where am I wrong in this code? 🤔
Why do you have 2 times sensor ?
i should be {{states('sensor.electricity_price_angshestre_120')}}
@deft timber Thanks, don't know how I missed that one...
I've got influxdb reporting my system uptime to HA in seconds like "35843" but I'm having trouble working out how to get it into relative_time format. I've tried passing something like as_timestamp(now()) - (states('sensor.influxdb_docker_nuc_uptime') | int ) to relative_time but haven't got anything to work :/
@bronze horizon have a look at this https://community.home-assistant.io/t/convert-seconds-to-days-hours-minutes/23152
@white ruin I guess one of your sensors reported "unknown" wich then is not a number - but thats only a wild guess
Hi, I have a question regarding a history_stats sensor. I'd like that sensor to store the value my heater has been on since september 1st. For that, I used the following conf:
- platform: history_stats
name: Heater ON
entity_id: switch.heater
state: 'on'
type: time
start: '{{ as_timestamp(strptime("01.09.2020", "%d.%m.%Y")) }}'
end: '{{ now() }}'
The value of the sensor is less than 6 hours while I know it has been on more than that. Is there anything wrong in my template? Thanks.
How many days do you keep in the DB ?
Configured in the recorder integration
By default it is 10 days
I did not configure the recorder so I assume it's set to 10. My history shows data only since september 30th (9 days then). However, within these 9 days, the heater has been on once during more than 8 hours. So the value should be greater than that.
If you try with start: '{{0}}' that will look in the whole history, the value seems correct?
@lapis quarry posted a code wall, it is moved here --> https://paste.ubuntu.com/p/k2DQmMC6BH/
Guess ill try that again..
Hey guys, not sure where to post this if here or in automations. I'm writing this automation where I'm trying to add a condition using a template but I cant seem to get it to work. Its the template in the condition I'm struggling with.
What I want to achieve is I have a set of input booleans that I would like to use as conditions and would like to use a template to choose the right boolean based on what entity triggered the automation.
you'll be better off using choose: in actions and define action depending on the trigger type
the action portion works fine
Its the condition template im struggling with: Im trying to carry the name from the trigger to the condition and it doesnt seem to work, it doest trow any errors in the logs but does not trigger..
the triggers are called device_tracker.keyring0xx and the booleans I want to evaluate are called input_boolean.enable_keyring0xx
Trying to use replace to change the name in the condition but not sure if that is right
If you try with
start: '{{0}}'that will look in the whole history, the value seems correct?
@deft timber I started with that and I got exactly the same value. While I'm at it, is there a way to reload sensors without restarting? I don't think so but I ask just in case.
the triggers are called device_tracker.keyring0xx and the booleans I want to evaluate are called input_boolean.enable_keyring0xx
Trying to use replace to change the name in the condition but not sure if that is right
@lapis quarry you need to remove the quotes around name. Now you are checking if the string 'name' is on. You want to check for the variable name
{%- set name = trigger.to_state.entity_id | replace("device_tracker.", "input_boolean.enable_") -%}
{{ is_state(name, 'on') }}```
Thanks 😊
I'm struggling to get a value_template configuration for an auto-discovered MQTT sensor (Tasmota based) working correctly. I'd like to avoid using a template sensor if at all possible. From the docs I see that MQTT sensors should be able to be configured with a value_template property which should be able to transform incoming values before representing them in HA. The sensor is a sonar distance sensor which measures a liquid ullage in mm, but I would like to see immediately the liquid level. I know the height of the tank is 1350mm, so I thought this should work:
value_template: '{{1350 - value}}'
Since the sensor is auto-discovered I tried overriding this property in the 'Configuration > Customizations' page in HA. Any help would be much appreciated
if its autodiscovered you cannot change that
you can't do stuff like that in customize
😦 too bad, I really liked the auto discover feature 🙂
Think I'll go with the template sensor then, Tasmota adds a bunch of useful stuff which I don't all want to have to configure manually
Thanks for the quick help!
you just configure an additional sensor manually, you can leave discovery on
hmm, right
its same but different from a template sensor
if you want to go deep you can use the discovery message from the current distance sensor to craft a new discovery message for water level and send it from Tasmota using a rule triggered on boot so the water level sensor would appear under the same Device as a new entity
@acoustic wedge If with 0 it gives the same result then I have no idea. Sorry. You can only refresh some sensor w/o restart, depending on their type. I think you only can for mqtt & rest sensor.
Thanks
Hey guys, one question: I´m just wondering if HA will allow to use a For loop to populate a list or entity_id in the trigger section of an automation?
trigger:
platform: state
entity_id:
- input_boolean.enable_keyring01a
- input_boolean.enable_keyring01b
- input_boolean.enable_keyring02a
- input_boolean.enable_keyring02b
- input_boolean.enable_keyring03a
- input_boolean.enable_keyring03b
I mean replace the above by this:
{% for boolean in states.input_boolean if 'enable_keyring' in boolean.entity_id %}
- {{ boolean.entity_id }} {%- if not loop.last %} {%- endif %}
{%- endfor %}
I tried this loop in the developer tools and it that returns the same list of entity ids..
Can this be done?
having hard time, i want something to happen when alarm goes on at android phone ( or like 30mins before). value_template: "{{states('sensor.date_time_utc') == (states.sensor.oneplus_a5000_next_alarm)| timestamp_custom('%Y-%m-%d, %H:%M') }}"
cant make the timestamp match?
@lapis quarry don't think you can do that...
Some expert hint/tip on the following problem would be nice. I run multiple Bluetooth temperature sensors. Usually, the data of an individual sensor is collected by a particular (I have assigned the one that is typically closest to the sensor) Bluetooth2WIFi bridge, converted to MQTT, and then processed by Home Assistant which works fine. However, since I use in total 5x Bluetooth2WIFi bridges, it would be nice to exploit some redundancy. The temperature data broadcasted by an individual sensor is often received by more then one bridge. So it would be nice to collect the temperature data into a single value that is then further processed by HA, e.g., the temperature data received by bridge 1 is used until another (for example the one received by bridge 2) overwrites it and so on. Can this be achieved by a template sensor?
Previously I have tried to achieve this behavior by letting all bridges report to the same MQTT topic. Although this works in terms of the data collection of the temperature values, it seems to cause problems with the broker.
@lapis quarry don't think you can do that...
@deft timber that is a shame, it would be convenient to be able to use templates there 😦
@lapis quarry sure but you could use a template trigger instead. And in the template you could test all you entities
Can anyone point me in the direction to figure out a template that is showing as unknown on my dashboard but works in the developer tools template page?
Can anyone point me in the direction to figure out a template that is showing as unknown on my dashboard but works in the developer tools template page?
@rain cove show us the shy template thingie
{{ ((states("sensor.sonoff01_total") | float) / (as_timestamp(states("sensor.date")) - as_timestamp(states("sensor.sonoff01_total_since")) ) | timestamp_custom("%j")|int ) | round(3) }}```
`sensor.sonoff01_total` float value (total kWh since below datetime)
`sensor.sonoff01_total_since` datetime
The goal of the template is to get the average daily kWh, so its total kWh / days since
either ypu can use that or maybe try different parts of your template without the operations one by one in lovelace to figure out where it fails,
I don't see any wrong from here :/
Darn. I guess I could look into having HA calculate it, thought it would be better considering the device basically already does it
One thing which I really hope isn't the issue but maybe it would be obvious to others is on startup, the values aren't populated so it tries to do timestamp - null and I get a type error. But wouldnt it try again once sensor.date updates?
TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'
(I am only assuming this error message is from my template, not actually sure)
one way to workround the undefined sensor state would be to use the statistics sensor in between I discovered
Hi all...so I'm trying to wrap my head around how to create an automation that compares the outside temp (sensor.dark_sky_temperature) with the inside temp of my house (sensor.hue_motion_sensor_1_temperature) , and then notify me to open the windows if the temp outside is lower than inside.
I know I need a logic comparison template between those two sensors, but I'm struggling how to correctly form the template and trying to figure out where I should put it in that automation (e.g. do I call a separate script to do the comparison as a trigger, put the template right in the automation as a trigger, etc).
Thanks for the help!
@dry matrix
trigger:
- platform: template
value_template: "{{ states('sensor.dark_sky_temperature') | float < states('sensor.hue_motion_sensor_1_temperature') | float }}"
goddamn teddy let him some tasks on his own 😄
Ok great! I understand better now. Thanks @buoyant pine !
@buoyant pine finally getting a chance to really look at what you sent me. Do you mind explaining it to me a little so I can build one of my own next time and don't have to ask for help? First 3/4 of the automation is pretty straight forward. My question is on the action itself.
- service: input_text.set_value
data_template:
entity_id: input_text.last_motion
value: "{{ trigger.to_state.friendly_name }}"
What is that actually doing?
It's dropping in the friendly name of whatever triggered the automation into the value of that input text entity
Also I meant "{{ trigger.to_state.name }}" 😅
so
what is the "input text entity"
and where is it dropping the friendly name
sorry trying not to be a pain in the ass
but would love to wrap my head around it so i can learn lol
i understand what a "template" is doing because your making sensor per say and that sensor "senses" changes in whatever you point at it. Changing it into a automation i dont understand whats thats doing exactly and how you could see that later on the frontend
I explained that earlier--create an input_text and display that in your frontend instead of the template sensor
This automation updates the input text with the name of the last motion sensor that detected motion @topaz walrus
sorry i guess thats what i didnt understand
never done an input text
ahhh
lightbulb moment***
so all the automation is doing is taking the name of the last motion detector triggered, and pointing it at a "input text card or whatever" thats listening
It's writing the friendly name of the last motion sensor that was triggered to an input_text entity
yeah figured it out
mind blown
didnt know that was even a thing lol
thanks so much for you help
Hello. I have a light template that if off, turns my lamp on moving slider 0-100%. I can also move the slider to 0% and the lamp turns off. The part I need help with is if the lamp is on I can not turn the lamp off using the template card toggle switch. When I try to turn it off, it turns back on. Any ideas?
I have a LED strip that activates when you enter a url (for example http://x.x.x.x/set?color=FF0000 )
I'm trying to figure out how to use the light template to set color. Any help?
@lapis quarry sure but you could use a template trigger instead. And in the template you could test all you entities
@deft timber How would a template trigger be written to include a For loop like the one I posted?
What I´m trying to achieve is being able to add or delete sensors that follow a certain naming convention and make it transparent to the automation, so I dont need to modify the code on every automation every time I add a sensor..
Is this possible somehow?
depends on the test you want to execute on the different entities values. If for instance you want to trigger your automation as soon as one of your sensor becomes true, you can do this:
automation: trigger: platform: template value_template: >- {%- set ns = namespace(ret=false) -%} {%- for boolean in states.input_boolean if 'enable_keyring' in boolean.entity_id -%} {%- if boolean -%} {%- set ns.ret = true -%} {%- endif -%} {%- endfor -%} {{ ns.ret }}
Interesting..
let me try this out see if I can get it to work
I have several instances where I would like to use it, one instance needs to trigger on every state change no matter the value, how would you write that?
specificaly its a timer: timer.keyring01a
Normally, the template is re-evaluated each time an entity in the template changes. So maybe simply by doing:
{%- for boolean in states.input_boolean if 'enable_keyring' in boolean.entity_id -%} {%- endfor -%} {{true}}
it will work ?!?
will try both and get back with the results
👍
this is the automation im trying to modify: https://paste.ubuntu.com/p/fkpZk8hxbX/
tried this but doesnt seem to work: https://paste.ubuntu.com/p/wfQf9nv8Xb/
actually forget that, it does work (My automation as initial state off so I need to re-enable it every time I reload automations)
it does work, amazing!! You just made my day, this is awesome 🥰
Wonderful
thanks very much, this is really usefull 😄
Actually I just noticed it has a weird problem.. 🤔
It works for 1 time only
Im reloading the automations, then I change the timer state to test and it triggers the first time, but then it will not trigger again when I change the timer state a second time...
Hmmm... I guess the empty for did not do the trick afterall....
I don't know how HA determines which entity to watch when analyzing a template
any other suggestions?
I guess i could use a if in the for loop
I want it to trigger on 2 states
active and idle
that might do the trick
dont know how to write it, trying to modify your first example but dont really know how this for loop works or what the namespace is
trying this:
the namespace is needed to manage global variable.Ootherwise the variable set in the loop are not global
Replace trigger.to_state.state with timer.state
Replace
trigger.to_state.statewithtimer.state
@deft timber ok, that worked, but i get the same result as the empty for loop, it triggers one time only on the first state change...
Gasp...
Why would it do that, makes no sense 🤔
I guess it is maybe because the first time it is triggered the template becomes true, and when something change again, the template is still true -> so no change -> no trigger
just a guess
is this related to the namespace?
no
it's because the automation is executed when the trigger becomes true, not just because it returns true
once again, just a guess
Indeed : Being a boolean expression the template must evaluate to false (or anything other than true) before the trigger will fire again
I see
just thinking if there is a way force the template to render false once it triggers
any ideas?
another idea. You create a template sensor, that will contain the number of timer matching your requirements (active or idle), and then you create a automation with a state trigger on this sensor, without giving from or to state (which will then be triggered at each change of the sensor)
Not sure if that can work? because I´m carrying the entity id of the trigger to the conditions and actions portion of the automation, maybe can be done but not sure how
you could store the entityId in an attribute of the sensor
but i agree, it becomes tricky 🙂
not sure if you can get that info in the sensor definition though
or you can also get, in your automation, the entity that changed in last, using last_changed
yes that might work also
sounds a bit complicated but maybe its just that I cant fully wrap my head around how the sensor_template would work
so basically it would be a for loop as you just described to list all timers but placed inside a template_sensor?
🤔
yep
you just need to make a sensor value that will change everytime one of the entity change (the number of entity with a give status, the sum of their last_changed, ...)
835``` is that all entities?
everything listed in the States page
Hello everyone, is there a way to extract time of latest mqtt message in a subject? The last_updated doesn't work.
There are messages with certain topic sent every second. I've set up a mqtt sensor that listens to the topic. The sensor works fine, but the last_updated value doesn't change.
you just need to make a sensor value that will change everytime one of the entity change (the number of entity with a give status, the sum of their last_changed, ...)
@deft timber
Been playing around in the template editor to see how it can be done, came up with this:
{% for state in states
if ( 'keyring' in state.entity_id and state.domain in ['timer'] and state.state == 'active' ) -%}
{%- if loop.last -%}
{{ loop.index }}
{%- endif %}
{%- endfor %}
seems to work in the template editor in counting the right timers that are active, but when i make a sensor using this its giving me a strange result:
here your sensor will contain the index of the last active timer. I don't think it is what you want to do
how would you do it?
I would do something like
{% for state in states if ( 'keyring' in state.entity_id and state.domain in ['timer'] and state.state == 'active' ) -%} {{ loop.index }}# {%- endfor %}
it will create a string with the indexes of all the active timer
ok, both seem to work now
lets see if i can get the automation sorted as you sugested
or you can also get, in your automation, the entity that changed in last, using last_changed
@deft timber
Been researching how to do this, from what I gather last_changed gives you the time a entity changed last but cant see how to display what entity was last changed in a domain (which is what I understand you are sugesting)
Do you have any pointers regarding this?
You can take inspiration from this: #templates-archived message
@lapis quarry what are you trying to do?
count the number of active timers?
I don't need a huge explanation, just a simple overview
end goal is trying to autopopulate a list of entities in the trigger section of an automation
best would be you read the last few posts you can she the "hack" im trying
now trying to write a template that will output the entity_id that last changed from a certain domain
are you just trying to remove the list of entity_id's?
i have a list of sensors in the timer domain, i want a template that outputs the id of the last one that changed in that domain
basicaly following slashback sugestion as a hack to achieve the results I want:
Have automations that auto-populate the list of trigger entity_ids when I add or detele sensors that will follow a certain naming convention
Yes but based on the most recent template changes, you'll only get an update every minute
at best
ok, I noticed the frontend was not updating was wondering why
the template editor was updating inmediatly so i assumed it might work
if you want it to update based on any change inside that group, make a group and then a template that uses the group. But I'm still not sure why you need a template for getting the 'last updated'
your current state trigger does that
which one
the one with this list:
- timer.keyring01a
- timer.keyring01b
- timer.keyring02a
- timer.keyring02b
- timer.keyring03a
- timer.keyring03b
none, it works fine
ok, so why are you trying to change it to the template trigger?
I would like that list to autopopulate when I add or delete timers
i have a case use for that as well
so i dont need to modify the automation every time
Ok, so this leads to the other problem I said: Templates in 0.116+ only update once a minute when you use a states or states.domain in your template.