#templates-archived
1 messages ยท Page 36 of 1
it goes with your template
post what you've tried
I use it currently in one of my macros. Makes it easy to avoid code reuse
https://dpaste.org/EwoWu it converts any entity (that's time) into seconds
Ok, i've tride to add the line:
{% from 'easy_time.jinja' import easy_time %}
to the configuration.yaml, but it gives me error:
Error loading /config/configuration.yaml: while scanning for the next token found character '%' that cannot start any token in "/config/configuration.yaml", line 156, column 6
In the Dashboard it says:
1 | {% from 'easy_time.jinja' import ...
------^
2 | type: entities
3 | entities:```
- That's not configuration.yaml
- It has to be in your template
wherever you put that template
- Templates cannot go in lovelace/dashboards
- That code you posted is dashboard code
My Sensor is in the configuration.yaml
type: entities says otherwise
that's lovelace
or "dashboards"
so your import needs to go inside configurtion.yaml in your template. If you say it's in sneosrs, then it goes inside your template sensor
{% from 'easy_time.jinja' import easy_time %}
{{ easy_time(states('sensor.valetudo_mistymemorablejay_main_filter') | float(0) * 60) }}
all in 1 spot
Ok in the developer tools under template it gives me "5 Tage". But where i have to add this code to take it in my lovelace?
yes ๐
I have a Template sensor for my electricity meter (tasmota)
Also, another question... your sensor.valetudo_mistymemorablejay_main_filter, does it have device_class duration, and unit_of_measurement: minutes?
Ok, so post what you have for that
@hot harbor I converted your message into a file since it's above 15 lines :+1:
@odd flare I converted your message into a file since it's above 15 lines :+1:
does this sensor seem correct? I want to set the rolling daily attribute value
@hot harbor Just add a sensor at the bottom of that file then
- sensor:
- name: RENAME THIS
state: >
{% from 'easy_time.jinja' import easy_time %}
{{ easy_time(states('sensor.valetudo_mistymemorablejay_main_filter') | float(0) * 60) }}
It worked. Thank you i'm totaly stupid
Did you rename it?
Yes, as Test123 ๐
Hehe, good, you aren't stupid, just don't know the system yet
now if you didn't rename it... then I might think you're a little slow ๐คฃ
FYI, the importing crap is very new
Like, 6 days new
so you won't really see many posts about it on the forums... or anywhere for that matter
seems a bit off to me
if you want it in a self contained template, it's going to be difficult
Thanks for your help.
I don't often work in Home Assistant, most of the time it works as it should, so changes are sometimes a bit confusing for me.
But I'll stick with the method with "timedelta" for now, that shows me the change/cleaning interval for the robot vacuum more nicely.
I'm pretty sure Fes's relative time may show it better. Easy_time is meant to be easy, but not highly configurable
Ok, and with Fes's relative time i have to add it the same way, right?
yep
@sand ivy I converted your message into a file since it's above 15 lines :+1:
@sand ivy templates resolve types. I.e. if it looks like a number, it will resolve to a number when passed to the config
Your only option is to template the entire params field
seems like the integration should handle this if it actually needs to be a specific type
params: "{{ [ my_string, '0', '1' ] }}"
yes, but that integration has been like this forever
I run into this like 4 times a year
"broken forever" == sad
for hte past... however long I remember
I'm not sure the dev's actually know
I'm not about to write it up ๐คฃ
I don't own one
Don't have one, don't care
na, it's more like "I don't own one, I can't test it out, not sure if this is a user thing or the integration but I know how to step around the issue"
The open source motto
along with its corollary - I have one and I shall make it work because I do care
Hi all. I'm a HASS newbie. I'm trying to create a template sensor that calculates the days remaining before an HVAC filter needs to be changed. I have this in my configuration.yaml, but am not seeing an entity created after restarting my HASS.
Pastebin link: https://pastebin.com/PU5RNKan
Any recommendations would be much appreciated!
got it. thanks m8.
Did you check your config in
-> YAML and restart HA?
@inner mesa - yes I did - no notifications w/ issues, but also no entity showing up in developer tools.
review the HA logs when you reload template entities
also, if you have another template: block in configuration.yaml, you need to include the new one under it and not duplicate it
@inner mesa - I checked to make sure I didn't have more than one template: block in configuration.yaml and i do not (thanks for flagging, though)
I checked the logs and pasted the relevant portion here: https://pastebin.com/19NwyczH
I'm not sure from the logs what I need to do - any suggestions?
I'm moving some duplicate stuff to the new jinja marcro's, great feature!. Is it possible not to return a new line on the end of the marco, so it it won't break some text lines i'm printing?
Properly use - jinja syntax
If you donโt know what I mean, read the first pin
Hello All, I have a history stats sensor I've set up in config to count the time a fan is on. It works but it doesn't update but every few minutes on the front end UI, Any ideas?
{% from 'foobar.jinja' import print %}
{{ print("sensor.foo") print("sensor.bar") }} ```
Since the template ends with a newline this will breakup the sentences as a result right?
Thatโs invalid syntax
You canโt execute 2 functions in 1 output
{{ print("sensor.kia_e_niro_ev_charge_level") }} {{ print("sensor.kia_e_niro_ev_charge_level") }}```
That will work but it will only break lines in markdown card
Yes I found out, adding a - to the macro
{{ states(entity_id) }}
{%- endmacro -%}```
Im trying to make a button on the dashboard that can toggle two services
action:
- service: water_heater.set_operation_mode
target:
entity_id: water_heater.egevej_8_tank
data:
operation_mode: "off"
and
action: - service: water_heater.set_operation_mode
target:
entity_id: water_heater.egevej_8_tank
data:
operation_mode: "heating"
how do I go about this
put them in a script and run the script from your dashboard button, but this is something for #automations-archived
oh, seems you were sent here from there
Hi Guys, may I get some help here please. I have created an MQTT binary sensor, the topic either sends 0 or 1 , but I want it display "Empty" and "Not Empty" , however I get OFF/ON only ๐ฆ
binary_sensor: - name: "Washer" state_topic: "/washer/Out/state" value_template: "{{ 'Not Empty' if value == '1' else 'Empty' }}" payload_on: "0" payload_off: "1"
Any help is appreciated
binary_sensor are only on/off. If you want the state to be a custom string, you need a sensor
Thanks! would I still be able to use payload_on / payload_off with sensor?
I don't see that as an option: https://www.home-assistant.io/integrations/sensor.mqtt/
Hi all,
I'm trying to build statistics on the amount of time a button is pressed and display that in a graph...
Idea is to provide the sum of the button presses for the last 5 (or perhaps 10) minutes.
(underlying context: my girlfriend is expecting and I'm trying to build a counter for the contractions... every time she feels one, she would click a button. Stats would help to keep track)
alternativily, having stats on the interval between the presses would also work
is it possible to use templates to see if an entity is in a zha group
I don't expect your girlfriend will be very happy she has to press a button while having contractions, she will probably have something else on her mind
But you can look into this
Are they listed in an attribute of the group? Or something similar
the entity of the zha group, lights.kitchen_lights makes no mention of lights.kitchen_lights_1 or lights.kitchen_lights_2, at least, not in developer-tools/state
How do I combine these two
switch:
- platform: template
switches:
blind:
friendly_name: "Blind"
value_template: "{{ is_state_attr('switch.blind_toggle', 'sensor_state', 'on') }}"
turn_on:
service: switch.toggle
target:
entity_id: switch.blind_toggle
turn_off:
service: switch.toggle
target:
entity_id: switch.blind_toggle
With
switch:
- platform: template
switches:
blind: ??
turn_on:
action: - service: water_heater.set_operation_mode
target:
entity_id: water_heater.egevej_8_tank
data:
operation_mode: "off"
turn_off:
action: - service: water_heater.set_operation_mode
target:
entity_id: water_heater.egevej_8_tank
data:
operation_mode: "off"
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
You've shown both the template switch and the service calls. You put the part that you want to run when the switch turns "on" in the "turn_on" part and the other part in the "turn_off" part
it's not a matter of "combining", but understanding what you're doing
Any reason this only updates every minute or so? https://dpaste.org/fBGiS
now()-based triggers only update every minute intentionally, so it doesn't overload the system with events
Ahhh I could of sworn my old pool* filter timer set the same way would update real time.
Is there a solution for a more real time run timer?
Probably using https://www.home-assistant.io/integrations/timer/ somehow at a guess
Logger: homeassistant.helpers.script
Source: helpers/script.py:1068
First occurred: 10. April 2023 um 00:00:00 (978 occurrences)
Last logged: 01:00:29
Error in 'choose[2]' evaluation: In 'template' condition: UndefinedError: 'None' has no attribute 'state'
``` Where can I find or how can I find the error ?
That's a history stats, the template itself only has "now" in it, so it will only update once a minute. Templates that contain entity_id's will update on the minute and on the entity state changes
your second choose in a script has the error.
is there a way, where I can narrow the error down? I went through all of my scripts and searched for choose... but I didnt find any element which doesnt exist anymore or where the state can be wrong.
Those only count down.
Is there a solution you know of for a more real time run timer?
you don't want it searching the database anymore than it is
all you're going to get is slightly more resolution
@mental violet the error says exactly what the error is. You're trying to use somevariable.state when somevariable is None (ie: no-value)
in a template
paste your template code that includes "choose[2]"
I have many scripts for a LoveLace Button when it has to do more than 1 thing after being pressed.
But I will look into templates as well.
It's probably not in scripts.yaml - it's probably a tempate
just grep 'choose' in *.yaml in /config
or configured from the ui
how many do you have? just look through them in UI if you need to
PS: I never made/used a script; but error looks like common template-style issue
I have many scripts for a LoveLace Button when it has to do more than 1 thing after being pressed.
But I will look into templates as well.
I think if you up your debug log level you might get more info about what is running right before that error is thrown
it could be something in an integration too I think
Is it something that has happened nearly 1000 times in ~24 hours? There can't be too many of those?
How can I up my log level? I am seeing HA Core
The error is a template error. The pointer is inside a script or automation
it's the second condition in a choose
the template will have states.xxx.xxx.state as the method you used to get the state
or possibly trigger.to_state.state / trigger.from_state.state
you can problably search your files for .state
I'd try:
logger:
default: info
anyways if it's a xxx.xxx.state, you most likely have a missing entity, or renamed something
Yes thank you, I found it I searched for states.*.state. Thank you!
So, where was it, what's the yaml? Maybe we can tell you what sensor or value it's missing?
It was in templates.yaml where a template condition compared 2 variables with old names. In addition I fixed every state.xxx.state to the better variant states('xxx'). Thank you for your help
Ya, that's what the template help pages say. So all fixed?
Yes thank you for your fast help
np
@copper blade I converted your message into a file since it's above 15 lines :+1:
Just create a daily utility meter sensor out of your hourly sensor. That will give you the daily total
If you really want to use a template sensor, that will be quite complicated, and will probably go wrong at some point
But you can try the following:
0) remove the availability template, you don't want it to become unavailable, as you need to store the old value
- check if both the to_state and from_state of your sensor are numeric
- if so, check if the to_state is higher than the from_state (otherwise there was an hourly reset)
- calculate the difference if the from_state is higher, ortherwise take the from_state
- add that difference to the current state of the template sensor
- in any other case, return the current state of the template sensor again
device_entities(devid) returns a list with entities, the list has a find() function, but how i regex match specific element from the list?
find() don't permit regex, only simple string
search allows regex
devcice_entities('banana') | select('search', '^light.') | list
{%- set dev.name = device_attr(devid, "name") %}
{%- for ent in device_entities(devid) %}
{{ent.find("(?:_version)(?<!_newest_version)$")}}
{%- if ent.find("(?:_version)(?<!_newest_version)$") |int>=0 %}
{{ ent }}
{%- endif %}
{%- endfor %}
{%- endfor %}
i have try {{ ent | select('search', ".*(?:_version)(?<!_newest_version)$") | list }}
but is not working
what are you trying to achieve here
so far you are working with entity_id's, but it looks like you want something from the attributes of those entities
i want to check if _version exists on device entities
because device_entities return version and _newest_version
and on a simple find, returns both
and i need to regex one of them
your ent variable will be an entity id, for example update.mariadb_update
exact, but is a list
there will never be _version or _newest_version in that entity_id
update.tasmoadmin_update
sensor.tasmoadmin_version
sensor.tasmoadmin_newest_version
sensor.tasmoadmin_cpu_percent
sensor.tasmoadmin_memory_percent
binary_sensor.mosquitto_broker_running
update.mosquitto_broker_update
sensor.mosquitto_broker_version
sensor.mosquitto_broker_newest_version
sensor.mosquitto_broker_cpu_percent
sensor.mosquitto_broker_memory_percent
binary_sensor.samba_share_running
update.samba_share_update```
hmm, okay
I only have update entities in that list
ah wait, I didn't enable those
you could also get the installed version out of your update entities
yes, but the new version avalibile no
anyway, this works for me, there is no need for a for loop (let alone a nested for loop)
{% set devid = integration_entities('Supervisor') | map('device_id') | unique | list %}
{% set ent = devid | map('device_entities') | sum(start=[]) %}
{{ ent | select('search', ".*(?:_version)(?<!_newest_version)$") | list }}
the newest version is also in the update entity
ok, i will test now, you code is working, i will try to make us of it
If I want to use templates, do I past the code - via the /developer-tools/template or ??
you put the template in a field which accepts them. devtoops > templates is used to create/check them
{%- for ent in device_entities(devid) %}
{{ ent is match(".*(?:_version)(?<!_newest_version)$") }}
{%- endfor %}
{%- endfor %}```
i manage like this
why the for loop? It is not needed
because the secound loop i create specific chips based on the find
yes, but you are still using a for loop now
and I showed you above that you don't need a loop at all
a field ?
is this for auto entities? Can probably be done without the namespaces and for loops as well, but I'm at work right now, so no time to look into it ๐
It might be easier if you just explain what you want to do with a template
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
I want to toggle these to services here on my dashboard
service: automation.turn_off
action:
- service: water_heater.set_operation_mode
target:
entity_id: water_heater.egevej_8_tank
data:
operation_mode: "heating"
service: automation.turn_on
action:
- service: water_heater.set_operation_mode
target:
entity_id: water_heater.egevej_8_tank
data:
operation_mode: "off"
via a button if possible
still doesn't answer where you want to have a template
but it looks like you need to be in #frontend-archived
there you can ask how to assign a service call to a button on your dashboard
I was there yesterday but they send me here because they said that if the button needed more service calls, it should be "through" a template
Then you should explain more clearly what you want to achieve. Because so far I don't see the need for templates
And please leave your questions on the public channels, I'm not a personal HA support
I would like a button on my dashboard - if is heating and pressed it turns off (one service) and if its off and pressed it turns on heating (another service) - Its a water heater
still no need for templates, you can use a script with a choose or if action, and select the right action based on that
and then call that script by pressing the button
yes, auto enteritis but on Template side
Not sure if templates is the right place, but I need assistance with setting up entities that will differ based upon a selection.
I have thermometers for the bbq that I want to set up so when I choose an option (e.g. chicken or lamb) it will change what the gauge range is and change the timer etc
If anyone can point me in the right direction fir where to get started that would be appreciated
@hearty verge I converted your message into a file since it's above 15 lines :+1:
When using value_json with a binary_sensor what valid values will automatically be converted to the on/off true/false?
MQTT binary sensors have a payload on and payload off field. If your payload from your template does not match those, it will give you bad results.
so set payload_on: true and payload_off: false and you should be good with your value.isError template
or don't set those fields and match the output of your template to those fields
I actually just read this in the docs! But thanks!!!!!
Does that mean my True/False in my value_json needs to also be a string an not a true / false but rather a "true" "false"?
The answer does appear to be "yes"
which means I'll have to modify the JSON which shouldn't be too bad
payload_on string (optional, default: ON)
Says it needs to be a string...
Personally I just match "ON" or "OFF"
{{ "ON" if value_json.isError else "OFF" }}
Whats the flow to get a string into relative time?
{{value_json.metaData.lastUpdatedDate | as_datetime | relative_time()}} looks exactly the same on the ui as: {{value_json.metaData.lastUpdatedDate | as_datetime}}
My lastUpdatedDate is 2023-04-11T16:53:25Z
appears to work fine in tempalte editor
{% set lastUpdate = '2023-04-11T16:53:25Z' %}
AsIs: {{ lastUpdate }}
as_datetime: {{ lastUpdate | as_datetime }}
as_relative {{ lastUpdate | as_datetime | relative_time }}
returns:
AsIs: 2023-04-11T16:53:25Z
as_datetime: 2023-04-11 16:53:25+00:00
as_relative 2 hours
This is in a value template for a sensor... maybe i need to change the class perhaps
that last one is correct unless there's something you're not telling us
When i put that into the value template for MQTT -> Sensor it doesnt show taht way
I'm using a value_template in an MQTT discovery sensor and it shows as this: 2023-04-11T16:53:25Z if I'm using value_template="{{ value_json.metaData.lastUpdatedDate | as_datetime | relative_time()}}",
In the template editor it shows differently.
If i use device_class timestamp it still shows that way
Yes because thatโs what deviceclass timestamp does
So if i want an elapsed time since last update
do i use a device class? or skip out on that
Both do the same thing
Using the timestamp with ad_datetime letโs the ui handle relative time
I'd like my sensor to show something like:
Time of last update: 2 hrs 15 mins
Neither will output that
Oh thats perfect
thank you!
it says 3 hours ago
thats all i needed
and now i offer thanks
device_class="timestamp",
value_template="{{ value_json.metaData.lastUpdatedDate | as_datetime }}",
FTW
I.e. you always get the most significant number
Hey there.
If I have a variable called "speakers" with targets selector in a script.
What stop me to write this:
alias: Wait until speakers stop
wait_template: >-
{{ expand(speakers.entity_id) | selectattr('state','eq','playing') | list |
count == 0 }}
Does not work but I am sure I am not too far.
If the variable speakers contains a list of entity_ids, the code you posted will work if you remove .entity_id
I believe target selector is represented as
target:
entity_id:
- media_player.a
- media_player.b
But I am not 100% sure
Then this should work
wait_template: >-
{{ expand(speakers) | selectattr('state','eq','playing') | list |
count == 0 }}
Or:
wait_template: >-
{{ speakers | select('is_state', 'playing') | list |
count == 0 }}
I will try now
Hi all, how would I setup a sensor to aggregate another sensor which reports a energy production for the full last hour? I want to calculate an overall total. I tried this but SolarthermieGesamtleistung always reports the same value as solar_energylasthour.
- trigger:
# Aggregate hourly production of solar collectors to daily
- platform: state
entity_id:
- 'sensor.solar_energylasthour'
sensor:
- name: "Solarthermie Gesamtleistung"
unique_id: "SolarthermieGesamtleistung"
device_class: "energy"
state_class: "total_increasing"
unit_of_measurement: 'kWh'
state: >-
{{ (states('sensor.solar_energylasthour') | float) }}
๐ Yeah i have the hourly value and want to sum it up
I already gave you an answer here
#templates-archived message
So sensor.solar_energylasthour reports like 0.3 kWh for 10-11 am and 0.5 for 11-12 and so an
Oh I missed that sorry for double post
Thanks for the reply earlier - you mention it will be hard using template, so I will try to use the utility meter.
Is the hourly sensor a utility meter sensor?
Ok it still restore my sonos too early. It is hard to test but thanks for the help
No, it is a sensor provided by the mqtt integration of a solar module
Then I would suggest creating a yearly utility meter from that sensor
Then, after that, create a template sensor which has an attribute in which you sum the previous_period attribute of the utility meter on yearly basis, and you add the value of the utility meter to the value of that attribute
Or you use an input_number and an automation instead of that attribute
Ok I think I get it working. I add first a 1 second delay so it does not catch before it starts. Then I used speakers.entity_id and it does not cut... Thanks
I am now quite proud of my sonos notification script ๐ . I can pass a media, or message to use with cloud tts. It plays and then restore the snapshot when finished
is it possible to get a persons / users profile picture via template ?
tried some possibilities like user.image / user.profile etc
Hi Everyone!
I was using sensor.uptime as a condition in some of my automations that send notifications. Now, with the new option to reload the YAML without restarting HA, this sensor doesn't get reset and new notifications are sent every time i re-read the YAML. What would be your suggestion to detect that HA config was recently reloaded?
This is what i was using:
{{ ((as_timestamp(utcnow()) - as_timestamp(states('sensor.uptime'))) | round(0)) > 120 }}
{{ state_attr('person.name','entity_picture') }}
hello beautiful people
question about de-json-ifying data from a REST API
the data comes back like this:
{"inputs":{"lat":"36.09","lon":"-86.64","limit":"1"},
"errors":[],
"warnings":[],
"version":"3.1.0",
"metadata":{"sources":["Ventyx Research (2012)"]},
"outputs":{"company_id":"13216",
"utility_name":"Nashville Electric Service",
"utility_info":[{"company_id":"13216",
"utility_name":"Nashville Electric Service"}],
"commercial":0.1032,
"industrial":0.0661,
"residential":0.1026}}
and I am trying to pick off the utility_name, with commercial, industrial, and residential as json_attributes
but I've lost my mind, trying to deal with nested json
what's wrong with the nesting?
i don't know how to handle it..
My rest experience was XKCD;s json
which is nice and flat
yeah, thats the page I was aattempting to grok
I haven't used it before but blindly: $.outputs as the json_attributes_path and then what you have as json_attributes?
oh there's even a site listed for you to test it: https://jsonpath.com/
but it seems to be bouncing off my understanding
oh sorry I slightly misread what you had said, you wanted utility_name as the value_template
you wanted value_template: "{{ value_json.outputs.utility_name }}"
still not working, but that looks right
what did it do?
gave me unknown
unknown for/
for the value of the sensor
are you sure it's able to pull the json in that case
the json results I posted came from curl'ing the url
right but I mean from HA
passign the same url I passed to curl
you could try pasting in the example json_attributes code into your list and seeing if that works. dunno seems like it's straight forward enough that it might be some problem in retrieving it
If you share the yaml someone might be willing to test it out and fix it
Hey everyone - is there a way to pass a sensor value to select.select_option?
I'm trying to set my ecobee homekit controller preset based on a sensor value that is defined by a schedule, but while this is accepted as a valid call, it doesn't seem to work:
service: select.select_option
data:
option: "{{ states('sensor.downstairs_hvac_preset') }}"
target:
entity_id: select.downstairs_current_mode
thanks!
why do i get these slashes when going from GUI to Yaml?
- wait_template: "{{ is_state(\"switch.v2_hal_mvbox_stand_3\", 'off') }}"
and if i paste this in develop tools-->templates, its invalid๐ตโ๐ซ
because the GUI uses double quotes inside and outside the template, and therefor has to escape the quotes inside the template
it will be rendered correctly, but indeed doesn't work in the devtools
@opal pulsar I converted your message into a file since it's above 15 lines :+1:
That code will work, provided the preset exactly matches the available option. What is the value of downstairs_hvac_preset, and what are the available options for the select in developer tools?
it looks like he's using the service caller on dev tools -> services tab
which doesn't accept templates
what yes it does
it's a pretty common mistake
I just tested this ?
Unless something changed, it's never accepted templates
"The UI does not support templates, you can still use the YAML editor."
Looks like this was the fix, 2021: https://github.com/home-assistant/frontend/pull/8657
glad it does now ๐
Ya, I was just looking for it
myself
It was a PITA for years
I must have forgotten about it and the PSTD from dealing with no-templates in that area trumped my memory
Hey there! Which color names can I use in Home Assistant in templates? I tried HTML color names but not all seem to work. Can I also use hex color codes? How? ๐
Trying to reuse template macros. I have a file "/config/custom_templates/weather.jinja" which contains the macro eaqi_list. I call (in the template editor) {% from 'weather.jinja' import eaqi_list %} and I get an error TemplateNotFound: weather.jinja. What am I doing wrong?
did you restart after adding it?
ah, you mean reloading the templates is not enough?
the first time you add them, you need to restart
and reloading templates does not reload custom templates, it reloads template entities
ok, I did not restart after editing weather.jinja from empty to containing something. Let's see if this solves it
but do I now need to restart every time I tweak any macro in custom_templates?
or just the first time it is created?
no, you just need to call the homeassistant.reload_custom_templates service call
it's not a button in the UI
you have to manually call it from developer tools -> services or make a button that calls that service
ok restarting has fixed it. thanks a lot @mighty ledge Petro
๐
Thanks, Tim0 - Looks like it does work after all. The display on the ecobee app is a bit misleading, as it does not display "Home" "Away." It instead shows the high/low, since I have my T-stat set to automatic mode. Walking over to the wall display, it does show the correct mode displayed.
If i want to change the change the blue background of my google cast cards on the dashboard, can i use poster: url ? Or is it an different code, can't get it to work
source: Galaxy S8
type: media-control
entity: media_player.spotify_mvdl
@echo shard I converted your message into a file since it's above 15 lines :+1:
You can't do that
secrets can't be used in templates
Sometimes you can work around the issue with template sensors using the new template style instead of the old template style
in your case...
template:
- trigger:
- platform: state
entity_id: sensor.my_iphone_bssid
not_to:
- unknown
- unavailable
variables:
bssids: !secret home_bssids
binary_sensor:
- name: My iPhone
device_class: presence
state: >
{{ trigger.to_state.state in bssids }}
Thanks, let me try that
petro should teach a templates class haha
So I added that to my configuration and reloaded, but I can't see the new binary_sensor
when you add the new template integration you have to restart
Ah not just a Quick Reload then
reload only works if it's loaded in
after you add it once, reload will work on any new template you add
but the first one, you have to restart
OK, it's there now, but is set to 'unknown' even though the BSSID is in the secrets list..
Does it only update when the value changes...
yep
if you want it to check on restart, you need to add that trigger
and also add variables to that trigger too
You don't know how to add a trigger to that?
I've been coding for 40 years, but been using home assistant for 1 day ๐คฃ I'll get there
The problem is there seems to be a lot of different syntaxes so googling is taking time
I think the template system has undergone changes
template:
- trigger:
- platform: state
entity_id: sensor.my_iphone_bssid
not_to:
- unknown
- unavailable
variables:
bssids: !secret home_bssids
- platform: homeassistant
event: start
variables:
bssids: !secret home_bssids
binary_sensor:
- name: My iPhone
device_class: presence
state: >
{{ trigger.to_state.state in bssids }}
Declarative languages in DSLs tend to take a little longer to get your head around ๐คท๐ผโโ๏ธ
That makes sense, so the triggers are OR'd and the variable has to be defined on both triggers to ensure it's available when the template is evaluated for the binary_sensor state
I can pick stuff up pretty quickly usually
This is literally the first template I'm writing
So apologies for being a bit n00b
it's all good
So do I have to duplicate this template trigger for each sensor, or is there a more elegant way (blueprints?)
I don't like copy pasta
if you have multiple phones you're checking with the same list of bssids, then just copy/paste the binary_sensor with a different name
otherwise you'll have to come upwith a different way to represent the data
like a map
(dictionary - if you know software
Yeah, I understand dict/maps
ok, so...
home_bssids:
'****fd': sensor.my_iphone_bssid
'****13': sensor.sons_iphone_bssid
...
then
You could also put that list in a file in your custom templates folder, and import it
template:
- trigger:
- platform: state
entity_id:
- sensor.my_iphone_bssid
- sensor.sons_iphone_bssid
not_to:
- unknown
- unavailable
variables:
bssids: !secret home_bssids
- platform: homeassistant
event: start
variables:
bssids: !secret home_bssids
binary_sensor:
- name: My iPhone
device_class: presence
state: >
{{ bssids.get(trigger.to_state.state, None) == 'sensor.my_iphone_bssid' }}
you have to reverse the bssid lookup probably
The BSSIDs are the wireless access points in the house, so the idea is to have a simple presence sensor when a phone is connected to any of the BSSIDs in the list. So it's not unique to each phone, but there should be a unique binary_sensor per phone.
there, that would work
Also, my state is still 'unavailable' despite adding the start up check 
it's possible secrets are just strings
Yeah, I think they infamously are
then...
I tried an input_select, but I couldn't get that array in a template either
home_bssids: >
{ "****fd": "sensor.my_iphone_bssid", "****13": "sensor.sons_iphone_bssid" }
and...
template:
- trigger:
- platform: state
entity_id:
- sensor.my_iphone_bssid
- sensor.sons_iphone_bssid
not_to:
- unknown
- unavailable
variables:
inp: !secret home_bssids
bssids: "{{ inp | from_json }}"
- platform: homeassistant
event: start
variables:
inp: !secret home_bssids
bssids: "{{ inp | from_json }}"
binary_sensor:
- name: My iPhone
device_class: presence
state: >
{{ bssids.get(trigger.to_state.state, None) == 'sensor.my_iphone_bssid' }}
but you gotta make sure home_bssids is valid json
and if you're interested... read up on yaml anchors. It will shorten the code to...
template:
- trigger:
- platform: state
entity_id:
- sensor.my_iphone_bssid
- sensor.sons_iphone_bssid
not_to:
- unknown
- unavailable
variables: &bssid_variables
inp: !secret home_bssids
bssids: "{{ inp | from_json }}"
- platform: homeassistant
event: start
variables: *bssid_variables
binary_sensor:
- name: My iPhone
device_class: presence
state: >
{{ bssids.get(trigger.to_state.state, None) == 'sensor.my_iphone_bssid' }}
Oooo nice
your goal is to identify presence as HOME by using the sensors from the HomeAssistant Apps on each phone?
does your wifi/router not have a native integration?
Yes
I prefer BSSIDs are more secure/unique than SSID
hi all, what wrong with my formatting, here: it does not like something but I cannot figure it out: thanks
- name: recycle_collection
unique_id: c9ec687d-be8d-44cb-9943-980e539d3506
state: >-
{{ min(((state_attr('calendar.recycling_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
attributes: >-
days:
{{ ((state_attr('calendar.recycling_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
i agree. my question was whether you could do the same without the app property. In my case HA is integrated with Ubiquiti Wifi so it figures out if each device is home based on whether Ubiquiti sees the device on the wifi
error message:
Source: config.py:982
First occurred: 12:45:09 PM (2 occurrences)
Last logged: 12:45:44 PM
Invalid config for [template]: expected a dictionary for dictionary value @ data['sensor'][28]['attributes']. Got "days: \n {{ ((state_attr('calendar.recycling_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}". (See /config/templates.yaml, line 1).
I have Google Wifi Pro (which I deeply regret) and the integration isn't working
ahhh. i see. also, yours will have a great advantage to mine - disconnects will be faster
get rid of the >- on the attributes line and move it to the days line
mine takes 3-5 minutes (i forget what the wifi timeout is) until it treats the endpoint as offline
OK, feel like I'm getting close:
too late ๐
๐คญ
Secrets.yaml (obfuscated)
[ '...:fd',
'...:13',
'...:7b',
'...:29',
'...:6d',
'...:71',
'...:8' ]```
That should create a JSON array
@echo shard I converted your message into a file since it's above 15 lines :+1:
No errors, but still shows 'unknown' even when phone's BSSID is in array, and after restart...
well, you didn't relaly do it right
oh
that's not JSON
JSON requires "
That's a JSON array...
it's a json array with bad values inside
JSON strings can be quoted either way
Thank you sir ๐
Oh dear, I'm out of practice with JSON... dumb mistake
by all means, you can also go the route you're going
but your code and configuration will be 10x
if you use a dictionary instead of a list, your total config will be
template:
- trigger:
- platform: state
entity_id:
- sensor.iphone_1_bssid
- sensor.iphone_2_bssid
not_to:
- unknown
- unavailable
variables: &bssid_variables
inp: !secret home_bssids
bssids: "{{ inp | from_json }}"
- platform: homeassistant
event: start
variables: *bssid_variables
binary_sensor:
- name: My iPhone
device_class: presence
state: >
{{ bssids.get(trigger.to_state.state, None) == 'sensor.iphone_1_bssid' }}
- name: My 2 iPhone
device_class: presence
state: >
{{ bssids.get(trigger.to_state.state, None) == 'sensor.iphone_2_bssid' }}
ah, but there is an issue
since we added the second trigger
the template in state won't work
I'll have to come back another time as I have a work call
No problem, still isn't working for me sadly
But some good learning thank you
Need to figure out how to debug
If I wanted to add a friendly name to this sensor, is it an attribute?
The name: field provides that
The text provided there is slugified to the entity_id
And if you provide a unique_id you can change the name, entity_id, icon and area in the UI
you're right, I just changed it in the UI. thanks!
I'm trying to figure out how to create an even using the local calendar integration that runs every week (all day), from April 1 to Aug 31, every year? When I try to set this up, it works but only for 1 year. Would some sort of templating fix or automate this as I don't think its a function the calendar support (yet).
Hey there, what is the best way to determine the max precipitation probability in the next X hours from an hourly weather entity?
Essentially, how do I turn something like this (returns a list of dicts)
{{ state_attr('weather.my_weather','forecast')[0:3] }}
into this
[4, 15, 15]
Where each element in the list is the value for 'precipitation_probability' from each forecast dict?
{{ state_attr('weather.wf_udp', 'forecast')[0:3]|map(attribute='precipitation_probability')|list }}
->
[
40,
30,
20
]
Ah, map(). Perfect, thank you!
@icy ravine I converted your message into a file since it's above 15 lines :+1:
You can use a repeat for each by templating the datetime strings for all the days... I setup something similar to run on New Years to create my trash pickup calendar.
I'm going to try this, thanks!
Hi friends ) Maybe its a stupid question but i wasted half day and cant finish this )
i need and entity that will tell my thermostats in what mode they must run ( winter/summer mode ) , i wrote in my conf.yaml this code:
input_select:
thermostat_mode:
name: Thermostat Mode
options:
- Winter
- Summer
initial: Winter
now my problem is icon )) i cant do diferent icons for diferent states (( i found this one , them must change by himself as i understand but it does not work (
mdi:SunSnowflakeVariant
input_select entities have a fixed icon
you can use custom-ui and then use a template through customize https://github.com/Mariusthvdb/custom-ui
Yes. card-mod related but error is at least displayed as template-error/problem. Any clue, how to dig deeper to see which template leads to this error message exactly?
what's the template? ๐
That is the question.
๐
It is a genaral error from my UI. So a lot of templates are in this page. And one is leading to this and I don't know which.
I suck at HA,
{%- if states('sensor.time') | as_timestamp >= '5:00' %} Good Morning! {% else %} Hey! {%- endif %}
Is throwing me and error that there's an invalid input, can someone point out my moronity?
{%- if now() >= today_at('5:00') %}
Good Morning!
{% else %}
Hey!
{%- endif %}
you were comaring an inteteger (timestamp) with a string
something like 18000 > "05:00"
If it's a template that's passed to the backend, i.e. it's jinja, it will output the error in your logs. If it's a template by someone who loads their own jinja lib, you might be SOL
anyone around, good at extracting data from a JSON in a template? i need a bit of help
it's also a template that's at least 81 characters long.
I wish I could use the excuse that it was early in the morning, But no I'm just an idiot ๐คฃ
Appreciate it @marble jackal !
can anyone point me in the right direction, if i want to extract the value from 17:00:00 each day, and from 21:00:00 each day.. and the days that the 21:00:00 value does not exist, i want to extract the lates value instead.. i cant figure out where to start from this JSON ?? https://pastebin.com/kfPVXGsD
https://pastebin.com/kfPVXGsD Pastebin'd for ya.
It was a template in a card-mod section. No further details in the logs. Because of this I thought, if there is another way to get nearer to the problem. At the end of the day I have duplicated the view and removed one card after another and then put the templates of the last card in the dev-tools and foud the problem. But ofc it would be faster, if I would be able to see the input with the error seomewhere.
figured I had enough guards here: {% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%} {% set data = watts.items() %} {{watts[nu] if nu in watts else 'No production estimated'}} and yet every now and then I see Template variable error: 'None' has no attribute 'items' when rendering '{% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%} {% set data = watts.items() %} {{watts[nu] if nu in watts else 'No production estimated'}}'
do I really need to add a guard on the attribute itself?
{% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %}
{% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%}
{% if watts %}
{% set data = watts.items() %}
{{watts[nu] if watts and nu in watts else 'No production estimated'}}
{% else %} Offline
{% endif %}```
yes
You can default watts to an empty dict
{% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts') | default({}, true) %}
I'm using a utility_meter to sum up the values of a sensor. This works, but I have one issue wich I don't see from the docs how I can solve it. The utility_meter shall provide the sum of the day. The sensor reports, how much energy has been consumed the last hour, so e. g. 9-10: 55 Wh, 10-11: 88 Wh, 11-12 110 Wh, ... 14-15 66 Wh. My issue is the utility_meter will not add the values from the sensor once the values start dropping. In the e. g. It will stay at 110 Wh (which was the maximum value on that day). Any ideas how to solve this?
utility_meter:
solarthermie_tagesleistung:
name: "Solarthermie Tagesleistung"
unique_id: "SolarthermieTagesleistung"
source: sensor.solar_energylasthour
cycle: daily
Sounds like maybe you want https://www.home-assistant.io/integrations/utility_meter/#delta-values ?
From the manual sounds reasonable - I'll give it a try thanks for your idea!
Is there 'best practice' for where to create/save templates, etc. please?
Watched https://www.youtube.com/watch?v=FfjSA2o_0KA recently and I realised there are probably plenty of ways to achieve something in Home Assistant but potentially some may be poor for performance.
I have a couple of integrations that provide 'measurement' (state_class) entities with a 'unit_of_measurement' in Watts. For my dashboard, I would like some of them displayed in kW to one decimal place.
While it seems possible to use the dashboard code editor to tweak a card label, is there a better/correct way? Helper?
{{ states('sensor.myenergi_zappi_XXX_internal_load_ct1') | float /1000 | round(1) }} kW```
you're just rounding 1000, BTW
nothing wrong with creating a template sensor for that
or do it in the frontend if the card supports it
why don't you just set that in the UI
click the entity, click settings, change your units and precision
deleted out of context reply
Ah, in this instance I don't think this specific integration is using the units in that way so changing them in configuration is not possible. I think many of the numeric values are being returned as strings, hence the need for the | float
no, that's a miss understanding on your part
all states are strings in templates
any entity (that's a sensor) added by the UI will have the ability to change the UOM or precision
if it's added via yaml, there's ways to get it to allow you to change those settings
Thank you. When I change the unit to kW and click 'Update' it seems to revert to W.
I tried via the dialog that's shown from the entity on both /developer-tools/state and /config/entities. Will try again tomorrow, maybe from the phone app.
it's the same dialog
they are not different
just do it in 1 spot
change it, click update and it'll be done
otherwise check your log for errors
Just tried on the phone app. It works fine for an entity in the Solaredge integration but not for the myenergi integration entity. I will submit an issue on the myenergi integration GitHub. I couldn't spot anything obviously related in the logs. Thanks for your help.
Hi all, wondering if someone can help me out with a cover template. I installed a zen16 relay for my garage with a zse43 tilt/shock sensor. The basic cover I was able to make and will paste below. What I would like to do is make it so if it was in the closed position, and then the shock is detected, it will show a status of opening, and vice versa. Not sure if that is possible.
`cover:
- platform: template
covers:
small_garage_door:
device_class: garage
friendly_name: "Small Garage Door"
value_template: "{{ is_state('binary_sensor.small_garage_door_window_door_is_open', 'on') }}"
open_cover:
service: switch.turn_on
entity_id: switch.small_garage_door
close_cover:
service: switch.turn_on
entity_id: switch.small_garage_door
stop_cover:
service: switch.turn_on
entity_id: switch.small_garage_door`
hi all does not work break
{% if character == ' ' or character == '|' %} {% break %} {% endif %}
I assume this is part of a for loop
please post the whole template, nog just a snippet
Just i need break "for loop" in certain case. How to it?
{# {% set vol=states('sensor.serial_sensor').split(' ')[5] %} #}
{% set data = states('sensor.serial_sensor') %}
{% set index = data.find('V') %}
{% set voltage = 0 %}
{% set multiple = 1 %}
{% set index = index-1 %}
{% for i in range(index) %}
{% set character = data[index-i] %}
{% if character != ' ' or character != '|' %} {%break%} {% endif %}
char={{ character }}
voltage = {{voltage}}
{%endfor%}
{{data}}
index={{index}}
error
TemplateSyntaxError: Encountered unknown tag 'break'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
@dusk sorrel are your running 2023.4?
Because the {% break %} function has been introduced in that version
ok thank you
Hi,
I've created a template sensor, however the sensor cannot be selected in the logbook (it does show up in history).
The sensor is not excluded from the recorder.
Any clue why ?
Read the "(!) Note" at the very bottom of https://www.home-assistant.io/integrations/logbook/
hi, does anyone know what I do wrong here? this works in the development tools templates but does fail when it's present in configuration.yaml
value_template: "{{ ((states('sensor.total_photovoltaics_energy') |float - states('sensor.smart_meter_ts_65a_3_energy_real_produced') | float /1000) + states('sensor.smart_meter_ts_65a_3_energy_real_consumed') | float /1000) | round(3) }}"
'Fail'?
2023-04-14 13:24:25.841 ERROR (MainThread) [homeassistant.bootstrap] Failed to parse configuration.yaml: while parsing a block mapping in "/config/configuration.yaml", line 1, column 1 expected <block end>, but found '<block mapping start>' in "/config/configuration.yaml", line 418, column 7. Activating safe mode
it's this code that gives me trouble ๐ฆ
energy_self_usage: unique_id: 'energy_self_usage' friendly_name: "Energy_Self_Usage" unit_of_measurement: 'kWh' ย ย ย ย ย ย ย value_template: "{{ ((states('sensor.total_photovoltaics_energy') |float - states('sensor.smart_meter_ts_65a_3_energy_real_produced') | float /1000) + states('sensor.smart_meter_ts_65a_3_energy_real_consumed') | float /1000) | round(3) }}"
I don't see anything obviously wrong in that snippet. It's probably in the context around it
if I use this all works
energy_self_usage: unique_id: 'energy_self_usage' friendly_name: "Energy_Self_Usage" unit_of_measurement: 'kWh' value_template: "{{ (states('sensor.total_photovoltaics_energy') |float - states('sensor.smart_meter_ts_65a_3_energy_real_produced') | float /1000) | round(3) }}"
only difference is that I added one more set of brackets and another calculation for a parameter
@clear mist I converted your message into a file since it's above 15 lines :+1:
Hi All, would this be a way to trigger an automation on a specific day, i.e. April 1st, every year
trigger:
- platform: template
value_template: "{{ now().month == 4 and now().day == 1 }}"
That's a way. I don't have any evidence, but I would wonder if using a time pattern to fire once a day, and a condition to check the date, would use less cpu than having to evaluate that template every minute forever.
yes! good point, how can this be made more efficient?
Use a calendar event trigger
That's a super easy and effective way!
Thanks again!
thinking about this, I would have to make an event in the calendar
but, when I try to use it as a trigger, it only gives me the option to select a calendar. not an event (at least in the UI)?
You'll get a trigger for every event of that calendar, you can narrow it down with calendar trigger variables in a condition.
https://www.home-assistant.io/docs/automation/templating/#calendar
i want to output the remaining time in minutes, but the output is not round ( 21.52974258263906 ), any fix?
thanks
{% if state_attr(timer,'finishes_at') %}
{{(as_timestamp(state_attr(timer,'finishes_at'))-as_timestamp(now())) /60| round(default=0) }}
{% else %}```
You're rounding 60
it's in second to minutes so /60?
in the (/60)?
No
sorry i'm noob, please let me know thanks
{{((as_timestamp(state_attr(timer,'finishes_at'))-as_timestamp(now())) /60)| round(default=0) }}
you're applying round(default=0) to 60
you need to apply it to the entire expression
you need parentheses, as I showed above
cool
hey guys, i'm trying to make a script to play specific media when a button on the dashboard is pressed - the script is the same except the title of the media, which will be from the button
i've got this code, which works, but i can only hardcode the value for INSERT_MEDIA_TITLE_HERE - i don't know how to make it based on a value from a button or something else
data:
media_content_type: EPISODE
media_content_id: >-
plex://{ "library_name": "TV Shows", "show_name": INSERT_MEDIA_TITLE_HERE,
"episode.unwatched": true, "episode.inProgress": [true, false], "resume": 1,
"sort": "originallyAvailableAt:asc", "maxresults": 1 }```
if anyone has any ideas on how to make this work, that'd be appreciated!
You can't use templates in a tap action, you need to use a script or automation
yeah, i figured it out - i've used a script with service_data values that i'm passing in from the buttons
hey guys, another question:
i'm trying to make 5-6 buttons that all call the same script with different service_data, and depending on the value of the service_data, i want it to do something
i'm stuck on how to get a script that can do 5-6 different things based on the service_data value? how would i make a script that does this? would i want to make an action for "wait for template", run the code and just end the whole thing in {{ true }}, or is there a better way?
hi folks, I'm trying to find docs on how to make sensor history graph smoother so it looks like this: https://1drv.ms/i/s!ApEDyMaCEAEellK2etKHeJqW0j22?e=y4rlMT
I have this template sensor that gives me open windows/doors as a text like "Open in bedroom", "Open in bedroom and bathroom window open" etc etc. Its a long one, can this be made in a better way? I just tried and tried until I got a good resault but sometimes I get Error while processing template: from it. https://pastebin.com/9VuMkx1m
Provide what you have so far. But generally you can pass arbitrary values to variables: that you define in the script, then reference the variables: values in subsequent script actions via a template.
https://www.home-assistant.io/integrations/script/#variables
i managed to figure it out not too long ago - i got the variables loaded in but was struggling mostly with what to do for if statements, but i've just gone with a choose and it seems to be working well so far ๐
it's annoying when things fail, but when it starts working finally then it feels good
To compile the list of open doors:
{% set open_doors = states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'door') | selectattr('state', 'eq', 'on') | map(attribute = 'attributes.friendly_name') | list %}
{% set ns = namespace(output = '') %}
{% for door in open_doors %}
{% if door != open_doors[-1] %}
{% set ns.output = ns.output + door + ', ' %}
{% else %}
{% set ns.output = ns.output[:-2] + ' and ' + door %}
{% endif %}
{% endfor %}
Then to pretty_print it:
{% if open_doors | length == 0 %}
{% set ns.output = 'No doors are open.' %}
{% elif open_doors | length == 1 %}
{% set ns.output = ns.output + ' is open.' %}
{% else %}
{% set ns.output = ns.output + ' are open.' %}
{% endif %}
{{ ns.output }}
Thanks!
I'd like to set up a template binary sensor that turns on when an existing binary sensor does, and only turns off when that same sensor and another sensor do (ideally for more than 10 minutes)
i can't seem to find any examples of how to do this though
template:
- trigger:
- id: 'on'
platform: state
entity_id: binary_sensor.1
to: 'on'
- id: 'off'
platform: template
value_template: "{{ is_state('binary_sensor.1', 'off') and is_state('binary_sensor.2', 'off') }}"
for:
minutes: 10
binary_sensor:
- name: Whatever
state: "{{ trigger.id }}"
keep in mind that it will be unknown after you first create it
then whenever binary_sensor.1 turns on for the first time, it will be on until the off trigger occurs. After that, the state will persist over restarts.
until the state of the target sensor changes, i gather
yep
I use a separate template.yaml, so I guess I put that trigger section outside of the sensor and binary_sensor sections?
no
that whole chunk needs to go together
post the contents of your current file that's separate. Also post the include you're using
config.yaml has
template: !include template.yaml
@fallow gulch I converted your message into a file since it's above 15 lines :+1:
which i'm guessing is not right
No, remove the - template:
Does for: work on template triggers.. TIL
I see it is mentioned in the docs ๐
The - trigger: line should be indented the same as the - binary_sensor: line
Is distance km or mi?
https://www.home-assistant.io/docs/configuration/templating/#distance-examples
it says km if you scroll up a few lines
Looking for some help with a template. this is just one part of my "morning brief" that is played each morning. I want it to print out (tell me) if a leak sensor was set off in the last 12 hours and which one it was. the "state" is either on or off and the reported attributes are: battery: 72.5, battery_low: false, linkquality: 123, tamper: false, temperature: 27.03, voltage: 2800, water_leak: false, device_class: moisture, friendly_name: G-Bathroom Leak Sensor water leak. This what I have and it does not error out but it also does not report if any of the sensors are set off. I have purposely set them off but I always get none have reported wet. ```
{% set leak_sensors = [
'binary_sensor.ac_leak_sensor_water_leak','binary_sensor.fridge_leak_sensor_water_leak','binary_sensor.g_bathroom_leak_sensor_water_leak','binary_sensor.lr_sink_water_leak_sensor_water_leak','binary_sensor.washer_water_leak_sensor_water_leak','binary_sensor.mb_birgit_leak_sensor_water_leak','binary_sensor.mb_joe_leak_sensor_water_leak',
] %} {% set twelve_hours_ago = now().timestamp() - 12 * 60 * 60 %} {% set
wet_sensors = [] %} {% for sensor_id in leak_sensors %} {% if
states(sensor_id) == 'wet' and as_timestamp(states(sensor_id).last_changed)
>= twelve_hours_ago %} {% set _ =
wet_sensors.append(sensor_id.split('.')[1]) %} {% endif %} {% endfor %} {%
if wet_sensors %} The following leak sensors reported a state of "wet" in
the last 12 hours: {{ wet_sensors | join(', ') }}. {% else %} None of the
leak sensors reported a state of "wet" in the last 12 hours. {% endif %}
You had initially said they report on/off (which is true), but then in the template you look for wet
Keep in mind, that template will only report sensors that are actively wet
You are 100% correct and I should have said I know the problem is I am using "wet" I had help in writing the above so I am not sure how to make it look for "on" and then tell me if that happened in the last 12 hours since again you are correct with your activley wet comment
And, you need a namespace var if you'll be appending like that
as_timestamp(states(sensor_id).last_changed) you need square brackets around the sensor_id here
No clue how to do namespace var where can I read up on that to see if I can make this work?
If you search on namespace in this channel you'll probably have enough examples
Thanks I will try that- one last thing would there be a "better" way to try and get the info I am going for?
You can do all that by just using filters, there is no need for a loop and namespace
Wait, maybe the storms append part
What are you trying to achieve
You only want the object_id right?
That can also be easily achieved
So I have a "morning brief' that HA speaks to me. I just want it to tell me if any leak sensors went off in the last 12 hours and which ones. Mind you I have automations that go off, scream over my speakers and blink lights etc. They work. I am just pisse dthat I can't get this to work so I am bull-dogging it!
I have automation that turns on lights in the evening by activating a scene, but I don't want it to touch lights that are already on. A script that iterates through the lights set in the scene and only takes action on those that are off perhaps. It gotta be based on the scene, I change it often, I can't hardcode lights and settings.
{{ expand(leak_sensors) | selectattr('state', 'eq', 'on') | selectattr('last_changed', '>=', now() - timedelta(hours=12)) | map(attribute='object_id') | join(', ') }}
You can't selectively apply a scene, you need to use a script then instead of the scene
Yeah, a script that reads the scene
I'm struggling with a template that can read the status of the lights set in a scene and save all the lights that are off to a new temp scene
What do you mean with reads the scene
Finds the lights set in a scene and then their status
Holy crap that was easy....not for me obviously...Thanks so much!
Still not clear what you mean by that, do you want to get it out of the YAML code of the scene?
You probably don't need to create the list, you can get all binary sensors using the right device class
Well, if I have two lights in my scene, one off and one on, I want it to check both entity_id's for their status, and save the entity_id that are not on to a variable
And read the scene.yaml for what settings the lights that are off should be set to, then add that to a new temp scene, then activate that scene, then wait a bit, then delete the temp scene
Unless there's a better way
{{ states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'moisture') | selectattr('state', 'eq', 'on') | selectattr('last_changed', '>=', now() - timedelta(hours=12)) | map(attribute='object_id') | join(', ') }}
im a lost puppy, looked at the docs of configuration/templating and no clue how to set it to none if no update for X minutes
I would not use scenes, and apply the right settings using a script
This shows as 11:3, any change to show 11:03?
var d = new Date(entity.last_changed);
return `${d.getHours()}:${d.getMinutes()}`
]]]```
That's not jinja, the folks in #frontend-archived can probably help better with JavaScript
This will be the time in UTC BTW
Oh OK.
{{ now() > states.sensor.device.last_changed + timedelta(minutes=10) }}
is this correct?
i want to set it to "none" or whatever if no update
This will be true if sensor.device has changed more than 10 minutes ago
can i set it to Null instead?
What do you want it changed less than 10 minutes ago?
if there is no update for 10mins, (true->true should count as an update) set it to Null
cuz my stuff will be uodated via api
{{ 'something' if now() > states.sensor.device.last_changed + timedelta(minutes=10) else 'something else' }}
'something' can also be none
template:
- binary_sensor:
- name: "Gaming Server "
state: "{{ none if now() > states.sensor.device.last_changed + timedelta(minutes=10) }}"```
looks good?
You have no 'else'
Which will mean it will always be none
else pass?
But if it's for a binary sensor you need true or false
So there is some device. You want to check if it has changed more than 10 minutes ago.
You want to use that in a binary sensor, which expects true or false for it's state template.
yes it's a server, either it's on or off, or the status is unknown
Also know that last_changed is reset after a HA restart, so it will always be true for the first 10 minutes after a restart
guess will set it to a minute then lol
but is this correct to get what i want?
No that will always return none
You can refer to this.state to get the current state
guess that should work
But that still doesn't make sense
how so?
Because the binary sensor state template expects true or false
can't it be undefined?
And you are feeding it none or the current state
So that will result in it being off (none) or off (current state)
so ill just go with int
It's like you're having a green fence and you are saying you want to paint it green, or the current color
int?
integer
cuz integer can be null definetly
but how does HA know someth9ing is " Unavailable"?
this is what i want to set the sensor to
You can define an availability template
Which is explained on the same page as I linked above
so then i would need 2?
yes, because i dont see how there isn't a simple setting to set it to "unvaiable" if no update
pretty sure someone did this before me
no clue, compleatly lost
Maybe it will help to explain what your goal is here, but I'm off to bed now
alrady did
this
and another server will just send api requests to ha letting it know if the server is on or off
but it should fail back to unavailable or null or whatever if there is no updates
I tried to do
{{ states.calendar.home_assistant.attributes.summary }}
to get the event title, but I got an error:
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'summary'
should i actually be using:
{{ states.calendar.home_assistant.attributes.message }}
instead?
.message actually works and gives me the event title, but i thought the summary was for that
maybe i'm remembering wrong
summary returns the title of the calendar event when you are referencing the trigger variable like trigger.calendar_event.summary.
message returns the the title of the current or next calendar event when referencing the state object of the calendar entity like states.calendar.example.attributes.message. or state_attr('calendar.example', 'message') The correct one to use depends on what you are trying to do.
so im using an automation that works based off when the home_assistant calendar triggers. so that makes sense
but if i want to debug, how do i see the summary in the templates? do i just use "message" to see it instead?
since it looks like i can only use summary when an automation is being triggered?
basically i want to see what the summary value is in the templates but i dont see a way to call it. only way i see to call it, is by using the "message" which appears to be the same value
The trigger variable only exist when the automation is triggered. The easiest way reliably test an automation that uses a calendar event trigger you need to use a test calendar event.
trying to test my event trigger but its not working for some reason, ugh
the trigger event data is all stored in the automation trace; click on "Changed Variables"
yeah i see the automation trigger but traces dont show anything, as if it never ran lol
ergh now i have to figure that out before i can figure out my summary / message issue
screengrab one of the traces; maybe you're not reading it correctly?
the timestamp on them never updates
im trying a cal event further out, just to see if maybe its not enough time to generate
there's some 15 minute rule on calendar triggers, like you can't create an event in the next 15 minutes I think
Note that calendars are read once every 15 minutes. When testing, make sure you do not plan events less than 15 minutes away from the current time, or your trigger might not fire.
well when i did it less than 15 min, i was reloading the integration
and it showed up, but i wonder if that still isnt working
so im just doing one really far out
quite a pain to wait that long in between tests
unsure if theres more that needs to get stored, etc
yeah it still didnt trigger after 30min something else going on i gotta figure out now lol ugh
platform: calendar
event: start
offset: "0:0:0"
entity_id: calendar.home_assistant
using this but now its not triggering with an event lol it did for months
why doesnt this trigger?
alias: calendar test fix
description: ""
trigger:
- platform: calendar
event: start
offset: "0:0:0"
entity_id: calendar.home_assistant
condition: []
action:
- service: notify.persistent_notification
data:
message: calendar has been triggered
mode: single
sorry i am asking in the wrong channel on top of that
is it possible in some way to, within a template, get the integration which an entitiy comes from
specifically i have a template that rejects devices with a source_type of router, but when the integration that the devices comes from (netgear) is reloading or off for any reason, that attribute disappears, which means the device(s) i dont want to be part of the resulting template show up anyways
and i figure if i can just specify devices that belong to that specific integration, it would just be simpler
You can use integration_entities() to list all entities of an integration
Ooh unaware that existed ty, that's perfect
Could someone help out?
Not sure what others think. But maybe changing how you check the server maybe more helpful. Instead of pushing updates to HA, why not have HA 'ping' whatever system your wanting to check on a timer with a short timeout to prevent hanging threads when the system is offline
That would require me to open a port on a esp8266 or arduino or sometimes a server that cant even open a port
Thought of that, but many servers have all ports closed
So that would require a lot of work
can I somehow combine if statements with template expressions?
@daring swan I converted your message into a file since it's above 15 lines :+1:
I want to calculate the approx cost of filament for a print and for that I need to apply a factor based on the filament used (which I get from the filename of the print)
Not like this, you can either put the whole calculation in every part of the if statement, or set a variable
yeah I went the variable way
@daring swan I converted your message into a file since it's above 15 lines :+1:
Can I somehow access historic values of input_text?
@thorny canyon I converted your message into a file since it's above 15 lines :+1:
@thorny canyon I converted your message into a file since it's above 15 lines :+1:
Hey, I could really need some help with the "Message" content of an automation notification. I setup the "Waste Collection Schedule", sensors for the different waste types, as well as a sensor for the upcoming disposal day.
The automation checks for the next disposal event and if itโs <2 days, it will send out a notification. I now want to include the waste type with the message, but canโt find the right variables to fetch it from the โupcoming disposal dateโ sensor.
Any help is much appreciated.
Find yaml configs above
This is the sensor Iยดm using for the notification (translated from German to English). I guess I canยดt use the garbage type in the message content, since itยดs not included in the "value_template"?
- platform: waste_collection_schedule
ย ย name: Next Disposal
ย ย details_format: "upcoming"
ย ย value_template: '{% if value.daysTo == 0 %}today{% elif value.daysTo == 1 %}tomorrow{% else %}in {{value.daysTo}} Days{% endif %}'
ย ย date_template: '{{value.date.strftime("%d.%m.%Y")}}'
ย ย add_days_to: 1
It looks like you should be able to get the type as an attribute
Why is it not possible to access old values of an input_text field? ๐ฆ
You can probably use an SQL sensor for that. And when using a state trigger you can get the old and new value from the trigger variables
But this is the same for all entities in Home Assistant, not just an input_text
hm so I would like to look at the last 10 values for a table
ah I cannot post a picture but imagine a picture that only shows a table with one line instead of the desired 10 ๐คฃ
why do you even want that
I want a table showing a log of the last 10 prints including cost
10 prints?
ahk, yeah. Sorry should've said that
just add the table to a DB and read data off that. or put it in google sheets / excel etc
Looks like something for a Google sheet
don't know why. HomeAssistant has so many things you can do that it overwhelms me ๐
It's built to automate your home, not to create spreadsheets
well I have all the data in Homeassistant and just search a structure where I can save it
you could have HA trigger writing into a DB / sheet maybe
the issue I'm having with going external is that I have all the data required to show already in HA and am just fighting to be able to access it in a way that allows me to list the prints on my printing dashboard
You could create 10 input texts and write the data to them on every state change (so it the first one the latest state, and then in the second one the previous state of the first one, etc)
add in a counter so know which one to write to next ๐
Or do something similar in the attribute of a trigger based template sensor
mh yeah that's DEFINITELY a kludge xD
If you ever play with nodered it's really easy to get historical data that way, with the history node.
give you all the states and attributes of a given time window
I was hoping that I could somehow access the old values that are obviously there as you can access them with the history view of the entity
Yeah I've always been a bit surprised there was not an easier way to retrieve the historical stuff. One of the few things I still go to NR for.
I guess maybe SQL sensor is the equivalent
but nodered is also on my bucket list. However I already had to learn python to get the duet3d integration to a state that allows me to get the necessary data into HA so I had to cut my complexity for the moment to get anywhere. But anyways, this has nothing to do with template-related stuff anymore
Hey everyone! Has anyone ever created a trigger using an event from the system log? I've read through the documentation and even tried the solution from https://community.home-assistant.io/t/automation-based-on-log/337925 but cant get it to fire...
What did you try?
I added system_log: fire_event: true to configuration.yaml In automations, I used evvent type: system_log_event for a trigger, under event data I've tried multiple values but nothing works. I simulate a log entry I use dev tools/services/System Log: Write Message: bevis
do you see events? I just added this to configuration.yaml and I see events that I could trigger on:
system_log:
fire_event: true
event_type: system_log_event
data:
name: custom_components.hacs
message:
- Could not update theme - Timeout of 60s reached
level: ERROR
source:
- custom_components/hacs/base.py
- 850
timestamp: 1681668750.1706276
exception: ""
count: 1
first_occurred: 1681668750.1706276
origin: LOCAL
time_fired: "2023-04-16T18:12:30.171734+00:00"
context:
id: 01GY5M9ETVGR2NK7W7MK94ZG6T
parent_id: null
user_id: null
it looks like it only fires events for "warning" and "error" (or higher, I guess)
handler = LogErrorHandler(
hass, conf[CONF_MAX_ENTRIES], conf[CONF_FIRE_EVENT], paths_re
)
handler.setLevel(logging.WARN)
@languid pendant I converted your message into a file since it's above 15 lines :+1:
great, that should work
So the problem I"m having is how to incorporate it into a trigger?
what did you try?
in automations / triggers / event type: system_log_event event data: data:
name: homeassistant.components.system_log.external
message:
- bevis
just share the trigger
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
you're describing it
platform: event
event_type: system_log_event
event_data:
data:
name: homeassistant.components.system_log.external
message:
- bevis
Wow
now it works thank you very much!!
one last quick question, lets say hypothetically the log entry contained a variable (i.e. "bevis 12") how would you create a trigger based on the word bevis alone, ignoring the number after it?
That thread shows an example: https://community.home-assistant.io/t/automation-based-on-log/337925/2?u=rccoleman
okay, I'll look into it! thanks again!
Due to recent changes to HA Calendars, so that 0 duration events are no longer allowed, an existing automation no longer runs. I'm trying to format a template to give me a correctly formatted end_date_time equivalent to "now() plus one minute". I've Googled about and found that end_date_time: "{{ (now().strftime("%s") | int + (60)) | timestamp_custom("%Y-%m-%d %H:%M",false)}}" appears to give me what I want in Developer Tools Template Tester, but doesn't work in the Automation. Can anyone point me to documentation that properly explains the change that has been made, as I presume it will include an explanation of how to format this correctly?
service: calendar.create_event
data:
start_date_time: "{{ now() }}"
end_date_time: "{{ now() + timedelta(minutes=1) }}"
summary: Test Event
target:
entity_id: calendar.test
This works, and the docs are here: https://www.home-assistant.io/integrations/calendar/#service-calendarcreate_event
Thanks, I'll try that. - Yeah, that worked beautifully, many thanks! ๐
I have trouble figuring this one out: I want to check a template condition against multiple values:
{{ trigger.to_state.state == "button_1_double"}}
something like that, but template condition compatible:
{% if states('trigger.to_state.state') in ("button_1_single", "brightness_move_up") %}
The trigger variable is already the state object, so you don't use states()
{% if trigger.to_state.state in ["button_1_single", "brightness_move_up"] %}
probably just need the test:
{{ trigger.to_state.state in ['button_1_single', 'brightness_move_up'] }}
I'm trying to convert a string to an int so I can use it in an if statement, but I think I'm converting it wrong because it isn't working. Is this correct?
{% set t = states('sensor.waqi_air_quality_data_waukesha') | int %}
Don't see anything wrong with this, it will give you a variable t which is the state of that sensor converted to an integer.
However, you didn't add a default for the filter, so you will get an error when the state is not numeric (eg unavailable just after a restart)
Strange. Because it's not working. I even tried attaching it to an input number to force it to update, and still nothing.
I'm trying to create an availability template for a couple of binary sensors, but can't quite get the syntax for determining if either of these are not available ...something like this:
"{{ not ['unknown', 'unavailable', 'none'] in [states('binary_sensor.nursery_occupancy'), states('binary_sensor.nursery_north_ptz_motion')] }}"
any help is appreciated!
Here's what I have for the state:
state: >-
{% set t = states('input_number.air_quality_force') | int %}
{% if 0 > t > 51 %} Good
{% elif 50 > t > 101 %} Moderate
{% elif 100 > t > 151 %} Unhealthy for Sensitive Groups
{% elif 150 > t > 201 %} Unhealthy for Everyone
{% elif 200 > t > 251 %} Very Unhealthy
{% elif 250 > t > 301 %} Hazardous
{% endif %}
That's because all of these statements can never be true
You are saying that 0 should be higher than t AND t should be higher than 51
All your >'s should be <
And you should probably have an else in case t >= 301
can you even have0 > t > 51 syntactically?
Yes, if you do 51 > t > 0
though that's confusing since, 0 > t, so t is negative? and then t > 51
ah okay, didn't know it let you chain up the >s
That was my point
ah, I was more commenting on just the syntax since I hadn't seen it before
am used to languages where you just have to add ands
Ah, it is allowed in jinja. ๐
Sidenote: Home Assistant wants you to set a default value when casting to int (or float). You'd do it like so: int(0) when using 0 as the default value.
I am trying to understand value_template in the context of this automation I am trying to create via the UI. The objective is to have an Action if my Deep Freezer temperature has been above 20 degrees for 10 minutes or longer. here is my current automation. I was told I need to put in a value template. My question is if I just want to have the trigger compare the actual to the current. Do I need the above value that was placed by the UI?
alias: Deep Freezer Notification
description: Happens if the Deep Freezer is above 20 degrees for 10 minutes.
trigger:
- platform: numeric_state
entity_id: sensor.h5100_1171_temperature
for:
hours: 0
minutes: 10
seconds: 0
above: 20
value_template: ' '
so could that be something as simple as {sensor.h5100_1171_temperature.current_temperature}
Perfect! I knew it was probably a simple logic thing my head wasn't wrapping around. Appreciate the assist.
Just leave that line out
And add attribute: current_temperature
so remove value_template? and add attribute?
Yes, if you want to trigger if that attribute value is above 20
- id: '1681672048461'
alias: Deep Freezer Notification
description: Happens if the Deep Freezer is above 20 degrees for 10 minutes.
trigger:
- platform: numeric_state
entity_id: sensor.h5100_1171_temperature
for:
hours: 0
minutes: 10
seconds: 0
above: 20
value_template: ' '
attribute: current_temperature
yes
How can I validate what the attribute names are on my entity?
This long method seems to give me an accurate result but I'm curious if there is a more efficient way to write this:
availability_template: "{{ not 'unavailable' in [states('binary_sensor.nursery_occupancy'), states('binary_sensor.nursery_motion')] and not 'unknown' in [states('binary_sensor.nursery_occupancy'), states('binary_sensor.nursery_motion')] and not 'none' in [states('binary_sensor.nursery_occupancy'), states('binary_sensor.nursery_motion')] }}"
Remove the value_template line. It won't work like this
In developer tools > states
will device_class: temperature have an attribute current_temperature?
when the integration reloads this causes issues with integration_entities([integration]) cause while the integration isnt active, the device is no longer associated with an integration. is there something like integration_entities('None') that i can use to check for?
no, device_class is the attribute and temperature is the value of device_class
usually the state is the temperature
Does anybody have an idea of how to write a condition that only allows an action if a door has been opened and closed more than a certain number of times?
I tried this example, but I don't think that it's correct.
- condition: template
value_template: "{{ states('binary_sensor.master_bed_door_sensor')|count > 2 }}"
enabled: true
Probably the easiest way would be to create a template sensor that increases in value every time the door State changes and have it reset when it stays in one state for however long you want the time out to be
I suppose alternatively you could do that with an Automation and a number helper
That sounds promising, but how would this be written? I'm a novice in yaml and jinja.
Look up input_number helpers in the integration docs. Setting it up with an automation should be pretty straightforward, you can use the UI for that
I'll give that a try
This seems to be what I needed. Thanks for the nudge in the right direction and for lending a hand when needed! Sadly, not everyone tries to be this helpful to everybody, but belittles or shows indifference instead.
I ended up with this...
if:
- condition: template
value_template: "{{ states('input_number.master_bed_door_open_and_close_count') > '4' }}"
enabled: true
then: - service: cover.open_cover
data: {}
target:
entity_id: cover.master_bed_shades - service: light.turn_off
data: {}
target:
entity_id: light.master_bed_lights
I've never had much joy with if: much prefer to use choose:
I'll be watching for any problems. I appreciate the help.
the reset to demo template button in developer-tools/template is going to drive me crazy
a lot of the mods here spend a lot of time helping others, i can understand why they may get frustrated at times. but i super appreciate their help, cause i know how frustrating other ppl can be
at any rate im happy to give pointers where i can
so i am still very much still new to more advanced templates...is there a less complicated way to do the following than what i have?
{% set ns.list={}%}
{%for group in json["listItems"]|selectattr("label","defined")|groupby("label.name")|list%}
{% set ns.group=[]%}
{%for item in group.list%}
{%set ns.group = ns.group + [item["display"]]%}
{%endfor%}
{%set ns.list = dict(ns.list,**({group.grouper:ns.group}))%}
{%endfor%}
{{ns.list}}```
hi all. I am using "serial sensor platform". But when not coming serial data, sensor.serial_sensor not be empty. How to decide it?
- platform: serial
serial_port: /dev/ttyUSB0
baudrate: 115200
With the new behaviour of today_at in 2023.4, can I still use it in template triggers? E.g. if I want something to fire at 9:01 once per 24 hours, what do I now need? Is the below, correct/wrong/overcomplicated?
{{today_at("9:01") < now () < today_at("9:02")
If you want something to trigger at 9:01 once every24 hours, my suggestion would be a time trigger
platform: time
at: "09:01"
but your trigger would also work, nothing really changed for your use case, template triggers without references to an entity_id were already rendered once per minute
Hmm, so leads me to worry: I also have a numeric conditions of some sort there, so in reality it's something like
{{ (today_at("9:01") < now () < today_at("9:02") ) or (states('sensor.bla')|float > 10) }}
How does this evaluate? Still once per minute, every time sensor.bla changes? Would it fire multiple times between 9:01 and 9:02 even if the second test if false?
Ah, but it will just be true at all times during 9:01, so it will actually fire once on the first change. Doh
Is that a trigger or a condition?
Hey, someone knows why these template in my template.yaml are not working?
- switch:
#Klimaanlage Bรผro
klimaanlage_buero_econo:
friendly_name: "Econo"
value_template: "{{ is_state_attr('climate.klimaanlage_buero', 'econo', 'on') }}"
turn_on:
service: tasmota_irhvac.set_econo
data:
entity_id: climate.klimaanlage_buero
econo: 'on'
turn_off:
service: tasmota_irhvac.set_econo
data:
entity_id: climate.klimaanlage_buero
econo: 'off'
that is a template switch, which belongs the switch integration and not to the template integration
so it should be in your configuration.yaml under switch:
or in an included file which is included in after that key
hey. I'm trying to sum specific values stored in an array and return the average of said values as the template state. however I'm failing miserable...
@novel crystal I converted your message into a file since it's above 15 lines :+1:
state is being returned as
state: >
,
,
,
,
,
,
,
-0.0745
thanks works now
{% set PMD = state_attr('sensor.omie_spot_price_pt', 'day_hours')[:7] | average %}
oh that's awesome, thanks @mighty ledge
I still get a weird state though, at least "visually"
state: >
0.0071
oh wait, my fault! sorted
@marble jackal When i wanna move these code vom template to binary_sensor what i need to change?
Present Check
- name: "Present Check"
state: >
{{ is_state('device_tracker.martin', 'home')
or is_state('device_tracker.iphone_von_arabella', 'home') }}
you change sensor: to binary_sensor:
when it is in the binary_sensor.yaml i dont need this step?
i think i need platform: template and so things?
template:
- binary_sensor:
- name: "Present Check"
state: >
{{ is_state('device_tracker.martin', 'home')
or is_state('device_tracker.iphone_von_arabella', 'home') }}
that should be the completed code after includes
im new in HA, i have think, when i use this sub *.yaml i can remove this first command: - binary_sensor:
thanks for correcting my script
you can probably
Hi everyone! how can I correctly pull out the datetime from an attribute to calculate a time delta? I tried this in a value template but it does not work: {{ now() - states('script.youtube_on_shield.last_triggered') | as_datetime > timedelta(minutes=1) }} (the error is: In 'template' condition: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Or some other way to confirm that the script did not run in the last minute...
states('script.youtube_on_shield.last_triggered') should be state_attr('script.youtube_on_shield', 'last_triggered')
{{ now() - state_attr('script.youtube_on_shield'. 'last_triggered') | as_datetime > timedelta(minutes=1) }} now the error is invalid template (TemplateSyntaxError: expected name or number) for dictionary value @ data['value_template']
It looks like you used a period instead of a comma
But you're not providing enough to properly debug
Whooops! Sorry! Corrected. Now the error is: In 'template' condition: TypeError: float() argument must be a string or a real number, not 'datetime.datetime'
Sorry about that! What else should I add?
remove |as_datetime
That works! Thank you very much! Could you quickly explain so I understand why here I don't need that?
It was already a datetime object, so you don't need to convert it. It's a terrible error message
Ahh, right! Thank you @inner mesa ๐
it's expecting to convert a string or timestamp integer to a datetime object, but it found a datetime object
Can I somehow check with a template if a specific state of a device happened in the last xx minutes?
(not the state in which it is now)
you would either need to use an SQL sensor to mine the history or a template binary_sensor that triggers on a state change of the entity to the state you want
for the latter, you're creating a sensor that captures the last time the entity was in that state, and then you can use the last_changed property for that
the second one sounds a lot simpler...
what am I'm missing here? works in dev tab. shorthand notation example looks pretty similar.
- condition: and conditions: - {{ (states("input_number.counter")| int) < ((states("input_number.target")|int) - 1) }}
quotes
oh ๐ฃ
Hey all, I hope I am posting on the correct channel. I need some assistance getting a value that has been returned from a ssh shell_command and manipulating the data. Anyone who can help it would be greatly appreciated.
I am trying to get the status of an outlet and when I ssh in and issue the command the result is "outlet is currently on: true" ... However if I assign that shell command as the status for a switch it doesn't understand the result so I need to manipulate it to show "1' any ideas?
๐ค What are you actually trying to do? Is HA unable to integrate w/ the outlet where you could just grab its state from HA itself?
hi all, I would like to use this a trigger for a choose option, and then for an if-then-else
- platform: numeric_state
entity_id: sensor.co2
id: HVAC
above: 1000
below: 1000
but, how do I create the condition if above 1000 then or else (below 1000)
Do you actually want 2 separate triggers? One above 1000 and one below 1000? That single trigger I don't think will do anything for you, since the above/below defines a threshold for triggering
i want both because I wanted a trigger for when CO2 is above 1000 ppm (i.e. CO2 levels are high), and then tell me that its below 1000 ppm (i.e. CO2 levels are safe)
yeah, I believe you want two triggers, your CO2 won't simultaneously be above 1000 and below 1000
oh, I would have to create 2 sepearate triggers then...
Yup, w/ separate IDs and use those IDs in your choose
got it, thanks
Correct the only option I have to integrate is using ssh
and are you using a template switch?
Yes as well as shell commands
Could you share what you've got on a code sharing site and paste the link here?
Hi all - looking for some help creating a template that will track my water bill, based on usage per month. I've tried a few things on my own and can't seem to get it to work quite how I want, so thinking that starting over with input from the community may be best. Here's what I'm working with:
- Billing cycle starts on the 18th of the month, goes to the 17th of the next month
- Bill is calculated based on gallons used per month:
1,000-5,000 gallons in a month = $4.81 per 1,000 gallons
5,001-10,0000 gallons in a month = $6.61 per 1,000 gallons
10,001+ gallons in a month = $9.62 per 1,000 gallons - A base fee of $12.03 is also added onto the bill at the end of the month
- I have a sensor that tracks the gallons used per day (sensor.main_water_line_today_s_water_usage) - again this is daily, so the sensor resets to 0.0 (gallons) at midnight every night (maybe I need another one to log each day, then reference that in the bill calculator?)
Thanks in advance for any input!
And what's the error you're getting
no error just not updating status
i don't think im using the value_template correctly
Does the command exit w/ a 0 code?
That is, does out1status exit w/ 0
and then dump Outlet 1 is currently on: true to stdout?
Also keep in mind, in your initial question you said "outlet is currently on: true" and casing is significant
so how to i test for this
im sorry i don't understand
this is incorrect the text in code is correct
Easiest way.... from a shell
out1status
echo $?
Command failed (with return code 127): shell_command.status_outlet1
Well that sounds like a separate problem.... or the command never worked?
out1status is correct? It's not like outlet1 status?
it works from shell
the command works when issued from shell but when issued from HA i see that error in logs
From shell... on 192.168.6.170?
I'd probably just have a nightly automation that increases a monthly counter (like an input_number helper) by the value of the daily sensor, right before it resets. Once you have the number of gallons used in that billing period, calculating the price should be pretty straightforward with a template.
Though I'd also check if there was a way to make my data fit into the energy dashboard for water.
I'd throw on debug logging for command_line to get some more verbose output to see what's up. 127 is command not found
Add homeassistant.components.command_line: debug to your logger: in configuration.yaml
and restart
ok but before i do that i just realized that i am also getting the same error in logs for the turn on and off
so i did some more testing and using the switch DOESN'T work but running the service in developers tools does
so i think the issue is in my switch config?
https://www.home-assistant.io/integrations/switch.command_line/#command_on it's the actual command it'll run, not a reference
ohhhh
Thanks for the input! I do have the water consumption in the energy dashboard, but currently without a cost associated since the cost varies based on usage and the 18th is the cycle so I didn't know how to integrate it here (I'm a noob)
thanks so much testing this now
You're welcome
Ok switch is working, status isn't but I'll test a few things first
What is the maximum character length of an Entity Attribute (not for the State which is believe is 255)?
I believe that it's quite large, like 32k, but only to avoid causing DB perf issues
ok unfortunately i am still not getting the status of the switch
Back to debug logging ๐
excuse my ignorance i have debug logs on but dont see where to find the logs
the normal home-assistant.log file
I d probably just have a nightly
@icy ravine I converted your message into a file since it's above 15 lines :+1:
i am using serial integration. How to buffer last 10 data with end \n\r or 250 characters?
You need device_class: water and state_class: total_increasing
the state_class can not be set in the legacy template sensor format which you are using
ow wait
it's only the price, sorry
you need unit_of_measurement: currency/unit
so eg $/gal
@mighty ledge if I use something like set foo = bar | default() and bar was not provided, what will foo be? I always assumed it was none but that doesn't seem to be the case, since foo is none returns false, so I'm wondering what it will be? It surely is falsely, so something like iif(foo) will return false
same with a structure like set foo = bar if bar is defined (so without an else)
Iirc itโs an empty string
I use
| default(none)
Hello everyone, im new to HomeAssistant and i have a Problem. I try to get this template work. It works in the editor, but when i put it in the config.yaml and did a reboot, it shows as unavailable.
@digital harness I converted your message into a file since it's above 15 lines :+1:
Take a look at your log
what does it say
availability: states.sensor.shellyuni_e868e7f472ec_adc
that needs to be a template string
i deleted this part of the template. now it works ๐คฆโโ๏ธ
Thank you!
Yep you bet, if you want it to flip to unavailable, you will need to add that back, but actually have it be a template and have it return true when it's available.