#templates-archived
1 messages ยท Page 22 of 1
You could also just set a boolean helper to start with instead of going through MQTT
Ah. OK that makes sense, just setting the state for the tracker. I already have a tracker on her device, but I would probably do this for person.xxx
I wouldn't modify an existing device, or the person.
Mostly because if the device updates, the person will update and it will assume you're home
Sure. I could just make a new boolean to tell.
Yup ๐
It makes me re-think this, though
I have a presence/tracker for my mother which uses connected to my WiFi as device tracker/trigger
And it triggers when her iPhone reconnects to my WiFi, making it appear like se is coming to our house. Happends several times, and would be nice to by-pass. I do not want to install the app on her iPhone
How are you doing the connected to wifi test? I presume through a router integration?
In addition to Rosemary's suggestion on a prompt for a user to manually confirm if the house is empty, do you also have internal sensors that can tell if the house is occupied? Eg. PIR sensors. If the max time your daughter spends without moving is 20min, you could set the house to shut down if all PIR sensors are off for >30min.
I would be careful with that, if she's home sick or asleep then that might have undesired results
That's true too.
Can anyone clarify why this template would return a valid result in the Template Developer tool but cause the Check Configuration feature to fail?
sensors:
sensor name:
friendly_name: "Outside Temp"
value_template: "{{ state_attr('weather.home','temperature') }}"
Check configuration returns this specific error.
Invalid config for [sensor.template]: invalid slug sensor name (try sensor_name) for dictionary value @ data['sensors']. Got OrderedDict([('sensor name', OrderedDict([('friendly_name', 'Outside Temp'), ('value_template', "{{ state_attr('weather.home','temperature') }}")]))]). (See ?, line ?).
Because you've mismashed the old and the new template sensor format
template:
- sensor:
- name: "Outside Temp"
state: "{{ state_attr('weather.home','temperature') }}"
Interesting. And here I thought the VS Code addon was doing me a favor by "auto-completing" the template format.
It's only as good as it can be, there are other sensors which use a similarish format, but in general try to copy and paste from the docs and then modify if you don't know the syntax
Also, you can tell it's 3am, I messed up with the value_template above, it's state
{{ expand(states.media_player) | selectattr('state','eq','on') | rejectattr('attributes.browserID', 'defined') | list | count }}
How do I select all media player that is "on" and "playing"
selectattr('state', 'in', ['on', 'playing'])
Thanks RobC!
on and playing
Any device that has the states, "on" and "playing" will be counted
media_players specifically
My guess is a state of 'playing'
Yup
Anyway, that will do 'on' or 'playing'
ah, how do I do and
What, exactly, do you want to test, and for what?
Trying to create a card that tells me the number of devices that are turned on, or playing some media.
I think you mean 'or', anyway
Oh yeah
You keep dodging
states cant have 2 states, thats why
Alright
You are right, my bad, I phrased the question wrongly
What you gave was exactly what I wanted
Thanks!
I have one more question however.
{{ expand(states.binary_sensor) | selectattr('state','eq','on') | selectattr('attributes.device_class', 'eq', 'motion') | rejectattr('attributes.browserID', 'defined') |ย listย |ย countย }} Detected
How do I only display the motion sensors?
Probably that
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'
Getting this error tho
Ah nvm, I got it
You need to add a rejectattr like you already have
Oh wait
Or the opposite
Yeah I didnt, you are right about the reject
Thanks. Yes this is binary_sensor.door_window_open a group indeed. I got this now TypeError: '<=' not supported between instances of 'int' and 'str'
Remove the quotes around 3
Just figured that thanks.
hey all newb here, quick Q. And/OR is there a special for it? some way to (is_state('device_tracker.me', home) and/or is_state('device_tracker.partner',home)
or
((is_state('device_tracker.me', home) and is_state('device_tracker.partner',home)) or ((!is_state('device_tracker.me', home) and !is_state('device_tracker.partner',home))
thanks!
OH right
uh askin if it's... well... guess i was askin how i do? but i guess it's #2 via s/!/not and that'll do yeah?
If you're just checking for whether either one of two people is home, you can use the state of zone.home to see how many people are home
If you need to do more advanced things like check if specific people are home, while excluding others, then you'd have to resort to templates or other methods
i want to hide the map if we're both home or we're both out is all
so if zone.home's count is 1 then show, essentially.
yeah that works. danke
I have a scraper that produces a list of times over the next 24 hours in the format HH:MM. I would like to convert it to timestamps. For the times today, this is easy using the today_at filter, but whatโs the efficient way of doing it for the whole upcoming 24 -hour period.
I have a Zigbee2MQTT switch that changes from the state of the button that was pressed to blank so I made this:
- name: Living Room Table Switch
icon: hue:dimmer-switch
state: >
{% set action = states('sensor.living_room_table_switch') %}
{{ this.state if action is none else action }}
for some reason it won't work
I want the template to not show the state if its none
@thorny snow I converted your message into a file since it's above 15 lines :+1:
I have problems with using the new template format in packages.
I get "expected a dictionary for dictionary value @ data['packages']['sensor']"
It was supposed to be solved a year ago but dunno if it got broken again? https://github.com/home-assistant/core/issues/49212
#OPTION 1
#configuration.yaml
homeassistant:
packages: !include_dir_merge_named packages/
โ
#packages/solar.yaml
template:
sensor:
- name: "power solar total"
unit_of_measurement: "kW"
device_class: power
state: >-
{% set solar = states('sensor.inverter_active_power') | float*1000 %}
{{ (solar if (solar > 0) else 0 }}
#OPTION 2
#configuration.yaml
homeassistant:
packages: !include_dir_merge_named packages/
โ
#packages/solar.yaml
template:
- sensor:
- name: "power solar total"
unit_of_measurement: "kW"
device_class: power
state: >-
{% set solar = states('sensor.inverter_active_power') | float*1000 %}
{{ (solar if (solar > 0) else 0 }}
I don't think it's this file which causes that error. But I do see some issues here. I don't think you can use the same key twice in a package, and you are using template: twice
And please format your code as code
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Thanks, that was the way to get it formatted ๐
Yes, well I have tried without the second key altogether (and many more combinations) that was more to show that I have tried both ways.
If I remove these codes everything runs fine
Without the second key it won't work because you formatted them differently
One with - before sensor, one without
Yes but none of these ways work. Not alone and not together
Well, I'm sure that template works in packages, because I use it myself
Option 2 is correct btw, with the -
I get expected a dictionary for dictionary value @ data['packages']['sensor']
Yes, and because it doesn't say ['packages']['template']['sensor'] I would say it's caused by something else based on this error
hmm ok thanks I trust you and will continue to look ๐
Wait, I see the problem
It's your include
With this include it doesn't use the filename as name of the package
So you now named the package template
And then you are using the sensor integration, which is indeed expecting a dict and not a list
So you need to use
solar:
template:
- sensor:
- name: ...
Which will name the package solar
Or you need to use !include_dir_named
Ahhhh! Thanks!! Now it finally seems to work! ๐
Ok followup question... which is correct?
#OPTION 1
template:
- sensor:
- name: "power solar total"
- name: "power solar consumed"
#OPTION 2
template:
- sensor:
- name: "power solar total"
- sensor:
- name: "power solar consumed"
None of those is incorrect
But I would use the first one when creating two (or more) template sensors in the same YAML file
nice, thanks!
Hmm it seems that the sensor.power_solar_total will not show up and there is no error message. Isn't it supposed to be "0" at least at all times?
How do i error seek if I get no error?
homeassistant:
packages: !include_dir_named packages/
template:
- sensor:
- name: "power solar total"
unit_of_measurement: "kW"
device_class: power
state: >-
{% set solar = states('sensor.inverter_active_power') | float*1000 %}
{{ (solar if (solar > 0) else 0 }}
If you are still using include_dir_merge_named you still need to add the package name in the YAML
And it will be sensor.power_solar_total
Sorry using !include_dir_named now, i.e. that is not the problem
Yes of course, I hit many mistakes in the text here but it was correct in HA.
Still no sign of sensor.power_solar_total
configuration.yaml
homeassistant:
packages: !include_dir_named packages/
packages/solar.yaml
template:
- sensor:
- name: "power solar total"
unit_of_measurement: "kW"
device_class: power
state: >-
{% set solar = states('sensor.inverter_active_power') | float*1000 %}
{{ (solar if (solar > 0) else 0 }}
Did you reload template entities from devtools > yaml?
Yes, and that shows no error. However it seems like i get error if I restart the whole HA
Logger: homeassistant.config
Source: config.py:865
First occurred: 12:42:20 (1 occurrences)
Last logged: 12:42:20
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensor'][0]['state']. Got "{% set solar = states('sensor.inverter_active_power') | float*1000 %} {{ (solar if (solar > 0) else 0 }}". (See /config/packages/solar.yaml, line 31).
Yes, you are missing a closing parenthesis in the last line
You are right!
You could also do this BTW
state: "{{ [0, states('sensor.inverter_active_power') | float*1000] | max }}"
True! Thx!
I dunno if Nabucasa is slow today or if it's just my server but get Unable to connect quite frequent today
Edit: could be IPv6 config that I will have to look in to https://www.nabucasa.com/config/troubleshooting/
hi comunity
have a question about a counter i did
{{states.light | selectattr('state','eq','on') | list | count}}
do somebody know if it is possible to take away entitys inside the code?
rejectattr('entity_id', 'in', ['light.foobar'])
Thx @mighty ledge i will test it ๐๐ป
This is likely very easy for you all... is using is_state() better or is the way I am trying sufficient as well? Also getting the error below when trying to add the second condition.
{{ trigger.to_state.state == "Charging" && trigger.from_state.state != "Fully Charged" }}
says "Message malformed: invalid template (TemplateSyntaxError: unexpected char '&' at 40) for dictionary value @ data['condition'][0]['conditions'][0]['conditions'][1]['value_template']"
Here you need to use == because it's a trigger variable
If you were using an entity (e.g. light.bedroom), then you would want to use is_state because it will fail gracefully if that device is not available/ready yet (e.g. on startup) instead of causing errors
Why is it balking at my && is that not the correct connector?
oh geez, do I just use and instead of &&?
yes
it's jinja. and, or, if, else etc all words
How do I debounce this template so that it only says "Fully Charged" after it has been in that state for say 5 minutes
{% set chg_on = is_state('switch.wheelchair_charger_plug_relay', 'on') %}
{% set chg_current = (states('sensor.wheelchair_charger_plug_current') | float) %}
{% set chg_power = (states('sensor.wheelchair_charger_plug_power') | float) %}
{% if not chg_on %}
Off
{% elif chg_on and chg_power < 2.00 %}
Idle
{% elif chg_on and chg_power > 6.00 %}
Charging
{% elif chg_on and 2.00 <= chg_power <= 6.00 %}
Fully Charged
{% else %}
Error
{% endif %}
You have to switch to trigger based templates or track the time using math
Which would you suggest? This is just used to visually give a text representation of the power. I am not aware of triggers for template other than in an automation and this is just like a text sensor. Could you provide an example?
Trying to debounce this: https://imgur.com/a/jCW2szq
The docs explain it quite well, you can use the same triggers as you can in an automation
@spark wigeon I converted your message into a file since it's above 15 lines :+1:
I'm missing something, how do I set value_template based on something that is parsed to attributes?
presumably using the methods in the docs for processing incoming data: https://www.home-assistant.io/docs/configuration/templating/#processing-incoming-data
{{ value_json.value }} or whatever
I'm not sure how that relates to the json_attributes_path, though
you'll need to factor that into the expression
value_json[0].value kinda works, but gets the one that's the first one in json, not the one that is parsed as attributes. I'm wondering if I can access those in the value_template in any way.
not that I'm aware of
Oh man ๐ฆ
but you should be able to represent that path in the reference in value_template
it's just JSON, after all
What the are attributes used for at all then? ๐ฆ
for the entity that you're creating
And whatever you wanted to do with them. It's not just creating variables for you to reference later
in other words, just not for the use that you immediately have
Hi
@mint drift I converted your message into a file since it's above 15 lines :+1:
With these changes, the template will only display "Fully Charged" if the "Fully Charged" state has been reached for at least 5 minutes.
Getting weird reading for a templated sensor https://photos.app.goo.gl/RzrkqEmV6PieVCU5A afaik the binary sensor it is using is staying in state on
- platform: template
sensors:
dryer_runtime:
friendly_name: Dryer Runtime
value_template: >
{% set x = states('sensor.time') %}
{% set t = 0 if states('binary_sensor.dryer_status') == 'off' else now().timestamp() - states.binary_sensor.dryer_status.last_changed.timestamp() %}
{{ t | timestamp_custom('%H:%M', false) }}
icon_template: >-
{{ 'mdi:tumble-dryer' if is_state('binary_sensor.washer_status','on') else 'mdi:tumble-dryer-off' }}
- platform: template
sensors:
washer_runtime:
friendly_name: Washer Runtime
value_template: >
{% set x = states('sensor.time') %}
{% set t = 0 if states('binary_sensor.washer_status') == 'off' else now().timestamp() - states.binary_sensor.washer_status.last_changed.timestamp() %}
{{ t | timestamp_custom('%H:%M', false) }}
icon_template: >-
{{ 'mdi:washing-machine' if is_state('binary_sensor.washer_status','on') else 'mdi:washing-machine-off' }}
anyone have any thoughts?
@mint drift I converted your message into a file since it's above 15 lines :+1:
Pretty sure last_changed isn't just a state change, too. It could update and the state remains the same
@pseudo steeple Have you checked out: https://www.home-assistant.io/integrations/history_stats/, that might give you what you want and be easier
Hi there
How do I hide a custom template sensor from the UI?
In the GUI, it doesn't seem to have the radio buttons for "Enabled", "Hidden" and "Disabled"
Hmm... Settings -> Advanced Settings, you don't see the radios? Does it not have a unique_id?
last_changed only updates on state changes, last_updated also on attributes.
There is no update of both if nothing changes
Also, I believe you should group your sensors underneath the same sensors: key, you've got 2 of them in the post.
I manually created it in yaml. Does it need a unique id for me to edit it through the GUI?
Yep
You're welcome
Will I set the unique id to something like sensor.name_goes_here?
Can be pretty much anything you want, some use the sensorname w/ underscore like you've got, others use a GUID, but yeah that's fine
Got it, will try that
@stoic umbra I converted your message into a file since it's above 15 lines :+1:
seems not
I have a Zigbee2MQTT switch that changes from the state of the button that was pressed to blank so I made this: - name: Living Room Table Switch icon: hue:dimmer-switch state: > {% set action = states('sensor.living_room_table_switch_action') %} {{ this.state if action is none else action }}
for some reason it won't work
I want the template to not show the state if its none
{{ this.state if action is "" else action }}```
I tried that yesterday and go "TemplateSyntaxError: expected token 'name', got 'string'"
use "==" instead of "is"
{{ this.state if action == "" else action }}```
worked for the first initial press
but now its not changing
what do you mean?
it changed to "off_press" now it wont change to anything else
I am pressing the other buttons and its not changing
it should show "off_press_release" etc
is there a way to get the state from the event sensor?
event_type: state_changed
data:
entity id: sensor.living_room_table_switch_action
old state:
entity_id: sensor.living_room_table_switch_action
state: off_hold_release```
of course, but that's not your problem here
and there's no need to use the event to get the state
If I can just use the "old_state" that doesnt change like the state of the switch
use a state trigger and use trigger.from_state.state
I'll have to find some examples - I have never used trigger.from_state.state
there are lots of examples in the third link in the channel topic
already looking at them ๐ just trying to get my head around how I can use it here
- trigger:
- platform: state
entity_id: sensor.living_room_table_switch_action
sensor:
- name: Living Room Table Switch
icon: hue:dimmer-switch
state: >
{% set action = states('sensor.living_room_table_switch_action') %}
{{ trigger.from_state.state if action == "" else action }}
worked perfectly ๐
@devout haven I converted your message into a file since it's above 15 lines :+1:
that's annoying. here i was thinking i was helping by putting the entire situation in a single post. now it's sort of impossible to read.
It's best to put the code into a site like pastebin
i did.. it's in github gists. if you want i can re-paste the links.
Mainly the last service call piece
it's the set_color section from here: https://gist.github.com/codahq/dbc5865f5081022bf6c362f621c5929f
Have you tried to fix the #zigbee-archived light directly with say a quirk or similar?
i'm pretty new to home assistant. i don't know the best way to fix this. i just know i did it already on a z-wave device. so, no, i haven't. i hadn't ever heard of a quirk before you mentioned it and i googled it just now. do i need to commit to the zha code base to do that or can i have local quirks?
That I'm not 100% sure on, I use Zigbee2MQTT myself. But someone in the #zigbee-archived channel can likely point you in the right direction ๐
yeah, i'll try over there. thanks for giving me that option. i still want to understand why this doesn't work though. i want to learn home assistant and all of its weirdness. what did i do wrong on this template?
I suspect, but this is without diving too deep, that your params section isn't what it expects
hue: -{%- h %}
saturation: -{%- s %}
transition_time: -{%- transition %}`
h, s and transition are not defined here, and you're also not outputting data.
To output data you use {{ double curly brackets }}
and the template isn't a string
you are correct. it was that params. the error was pointing me to the parent data map so i never looked at thos.
Lucky guess points to me ๐
so, the reason i used the script syntax there was because i tried to {{ h }} and {{ s }} there but then it complained that h and s weren't defined. i coudln't figure out what is passed from the ui i guess.
i saw other templates that used {{ h }} and {{ s }}. i guess i should have asked first why neither one was defined for me.
the exact error message is Error loading /config/configuration.yaml: invalid key: "OrderedDict([('h', None)])" in "/config/gledopto_family_room_display.yaml", line 79, column 0
it's updated at that gist url
yeah, that was it. i guess i didn't understand why some were quoted and some weren't either. whatever the > is doing after a key seems to be like a multi-line string i guess?
It is indeed
i do not understand enough yaml. probably best for me to go do some reading there.
There are some useful links in the pinned posts ๐
again, thank you
You're welcome ๐
i can't get the quirk to work and the zigbee channel seems busy or uninterested. i have the template working however. the problem i have now though is that since i'm not giving definitions for level_template, temperature_template and color_template any time i go back to the entity the values are reset and are not synced to the device's state. what is the best way to solve this? should i create helpers to store the values or should i make zigbee calls to read the attributes? here is the updated template btw https://gist.github.com/codahq/dbc5865f5081022bf6c362f621c5929f
@frosty grotto I converted your message into a file since it's above 15 lines :+1:
The 1st sensor will return me a street name between a time, otherwise its None. I want the second sensor to use the street name and get lat and lon to create a device tracker.
try this...
change value_template: "Road name: {{ value_json['data']['place'] }}" in value_template: "{{ value_json['data']['place'] }}"
change resource: https://nominatim.openstreetmap.org/search?q= "{{ value_json['data']['place'] }}"&format=xml&polygon_geojson=1&addressdetails=1
in resource: https://nominatim.openstreetmap.org/search?q= {{states('sensor.location')}}"&format=xml&polygon_geojson=1&addressdetails=1
I cannot test the first sensor, no clue how to do this so am assuming it works and kicks back a streetname....you do not need the words "Road name" in its state imo...just the plain streetname
You are right about this, i write road name caz i show that in the front end UI as well. Indeed shouldn't be used if i am gona reuse the value.
I got these from the log
2022-12-29 16:20:13.010 DEBUG (MainThread) [homeassistant.components.rest.data] Updating from https://nominatim.openstreetmap.org/search?q= {{states('sensor.location')}}"&format=xml&polygon_geojson=1&addressdetails=1
2022-12-29 16:20:13.585 DEBUG (MainThread) [httpx._client] HTTP Request: GET https://nominatim.openstreetmap.org/search?q=%20%7B%7Bstates('sensor.location')%7D%7D%22&format=xml&polygon_geojson=1&addressdetails=1 "HTTP/1.1 200 OK"
2022-12-29 16:20:13.592 DEBUG (MainThread) [homeassistant.components.rest] Finished fetching rest data data in 0.582 seconds (success: True)
2022-12-29 16:20:13.593 DEBUG (MainThread) [homeassistant.components.rest.sensor] Data fetched from resource: <?xml version="1.0" encoding="UTF-8" ?>
2022-12-29 16:20:13.594 DEBUG (MainThread) [homeassistant.components.rest.sensor] JSON converted from XML: {"searchresults":{"@timestamp":"Thu, 29 Dec 22 08:20:13 +0000","@attribution":"Data ยฉ OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright","@querystring":" {{states('sensor.location')}}\"","@more_url":"https://nominatim.openstreetmap.org/search/?q=+%7B%7Bstates%28%27sensor.location%27%29%7D%7D%22&addressdetails=1&polygon_geojson=1&format=xml"}}
2022-12-29 16:20:13.595 DEBUG (MainThread) [homeassistant.components.rest.sensor] Data fetched from resource: <?xml version="1.0" encoding="UTF-8" ?>
2022-12-29 16:20:13.596 DEBUG (MainThread) [homeassistant.components.rest.sensor] JSON converted from XML: {"searchresults":{"@timestamp":"Thu, 29 Dec 22 08:20:13 +0000","@attribution":"Data ยฉ OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright","@querystring":" {{states('sensor.location')}}\"","@more_url":"https://nominatim.openstreetmap.org/search/?q=+%7B%7Bstates%28%27sensor.location%27%29%7D%7D%22&addressdetails=1&polygon_geojson=1&format=xml"}}
It seems taking it as string as well? Since the road name is None now, should't it be none as well? I expect it become like this:
https://nominatim.openstreetmap.org/search?q= none&format=xml&polygon_geojson=1&addressdetails=1
rest:
- resource: https://crd-rubbish.epd.ntpc.gov.tw/dispProject/api/line-status.ashx?lineid=244025
scan_interval: 30
method: GET
sensor:- name: "Location"
value_template: "Road name: {{ value_json['data']['place'] }}"
- name: "Location"
- resource: https://nominatim.openstreetmap.org/search?q={{ states.sensor.location.state }}&format=xml&polygon_geojson=1&addressdetails=1
scan_interval: 30
method: GET
template:
q: "{{ states.sensor.location.state }}"
sensor:- name: "lat"
value_template: "{{ value_json.searchresults.place['@lat'] }}" - name: "lon"
value_template: "{{ value_json.searchresults.place['@lon'] }}"
- name: "lat"
I used the above one (244025) and then het this : Road name: ๆฐๅๅธๆๅฃๅๆๅๅ่ทฏไธๆฎต299ๅทท20่
But 'ๆฐๅๅธๆๅฃๅๆๅๅ่ทฏไธๆฎต299ๅทท20่' cannot be used as string in the second sensor (not with me in EU)
This one seems to work wrt to getting the data, still openstreetmap cannot handle the non-latin part
@heavy crown I converted your message into a file since it's above 15 lines :+1:
when I use it for local street, it works fine for me
Got it, thx for the info and example! Will test it out
I probably need to convert the characters in to web based encoding
Just wanted to quickly feedback, giving it a unique_id worked! I'm now able to edit the sensor in the GUI.
awesome
OK, thanks @mint drift ! However, a few things I could use assistance understanding as I am not following the logic. First, for the {% set fully_charged_timer = fully_charged_timer + 1 %} to work, that means the script is reloaded/checked every second, correct? Assuming that answer is true, wouldn't the {% set fully_charged_timer = 0 %} and {% set fully_charged_flag = false %} be setting it back to zero and false respectively every iteration? The Fully Charged inside the {% elif chg_on and 2.00 <= chg_power <= 6.00 %} shouldn't that be Charging since it hasn't hit the 5 minute mark it should not yet be considered Fully Charged. Lastly, I don' see how the code will ever get to {% elif fully_charged_flag %} since logically it will always hit the elif prior because they have the proper values. Thanks in advance for your feedback and for trying to help me out!
You're correct that the script is reloaded/checked every second in this case.
Regarding the {% set fully_charged_timer = 0 %} and {% set fully_charged_flag = false %} statements, these are only executed when the charging process has stopped, as indicated by the if not chg_on condition. When the charging process is stopped, the timer and flag are reset to their default values.
Regarding the {% elif chg_on and 2.00 <= chg_power <= 6.00 %} condition, you are also correct that this block of code should be executed when the device is "Charging" rather than "Fully Charged". The current condition only checks if the device is still charging (chg_on is True) and that the charging power is between 2.00 and 6.00. This block of code does not check if the charging process has reached the 5 minute mark.
Finally, regarding the {% elif fully_charged_flag %} condition, you are correct that this block of code may not be reached if the charging process is still ongoing and the charging power is between 2.00 and 6.00. However, if the charging process is stopped before the 5 minute mark (as indicated by the if not chg_on condition), or if the charging process reaches the 5 minute mark and the fully_charged_flag is set to True, this block of code will be executed.
Hi I am trying to acces Weather entity values by using a text sensor and I was wondering wether it would only work with templating. I am driving a nextion disaply with a ESP32devkit1 ```
text_sensor:
- platform: homeassistant
id: tempo
entity_id: weather.casatrying to publish it (i.e. 'rainy') to a display using lambdas but no luck
then:
lambda: |-
ESP_LOGI("main", "Value of my sensor:", id(tempo).state.c_str());
id(nextion1).set_component_text("stanza.t3",id(tempo).state.c_str());```
This method works fine for me with other sensor which are reacheabel using the native API, so it must be something with the weather entity. Any hint? thanks
So I guess the problem is it never leaves that block of code with the 2 to 6 until I unplug the charger entirely. As long as it stays plugged in it has like a trickle charge that continually stays in that range. So without some other logic it will never get outside of that to see fully charged down below. Possibly moving the fully charged to above that so that when itโs true it hits it before it gets back down to the 2 to 6? Also the charger power is always on until a different automation turns the power plug off at which time the charger says itโs been idle for 10 minutes. so when I unplug the chair it says Idle, and then after the 10 minutes is when the actual power plug is turned off. Iโll look over what you said in more depth once I get back to my computer. Thanks for the additional info, I think Iโll still have some more questions once I get to look at the code again.
Again without looking at the code on the computer, I still think that if the power goes back up to above six, something needs to reset the timer to zero so that the five minute timer starts again when it gets back inside the 2 to 6. Otherwise it seems as though thatโs just a cumulative five minutes even if it has bounced out of that range say up above seven for a few minutes in between times that it goes back into the 2 to 6. Hopefully Iโm making sense here.
What is going wrong here? I have a counter entity that counts seconds. I'm trying to render it as minutes so used the following template: {{states('counter.badkamer_in_gebruik_seconden') | float / 60 | round(1)}} But for some reason it sometimes outputs values like '2.8333333333333335'
The rounding works fine on other sensors like a temp sensor
you're only rounding the 60 to 1 place with that template
ahh
{{ (states('counter.badkamer_in_gebruik_seconden') | float / 60) | round(1) }}
you should really set a default though for that float filter
Thanks!
I'm considering making a template that combines two switches (one that powers my PC on and one that shuts it down) but before I do so does anyone know of a way to accomplish this with a helper?
The Wake on LAN switch has the ability to call a service to shut down the machine
https://www.home-assistant.io/integrations/wake_on_lan
i am trying this
{{ย data.battery }}
but i get an error of "Input must be bytes, bytearray, memoryview, or str"
if i remove the from_json to decode the json, i see the data:
"msg_ver": 2,
"msg_seq": 1816,
"state": 8,
"battery": 64,
[...]
what am I doing wrong?
ah, it seems you have to | to_json | from_json for whatever reason
Are you sure it isn't JSON already?
You can probably just do {{ state_attr('vacuum.alfred', 'data').battery }}
When using to_json you made it a string
And when using from_json you turned it back into a dictionary
formatted json string
{% set data = {
"msg_ver": 2,
"msg_seq": 1816,
"state": 8,
"battery": 64,
...
} %}
{# Encode the data dictionary as a JSON string and store it in the data attribute #}
{{ data | to_json | set_state('vacuum.alfred', 'data') }}
{# Decode the JSON string stored in the data attribute and access the battery field #}
{% set data = state_attr('vacuum.alfred', 'data') | from_json %}
Battery level: {{ data.battery }}
Is there a way to keep the previous state even after a HA restart? Every time I restart HA the state changes to โNoneโ```
- trigger:
- platform: state
entity_id: sensor.living_room_table_switch_action
sensor: - name: Living Room Table Switch
icon: hue:dimmer-switch
state: >
{% set action = states('sensor.living_room_table_switch_action') %}
{{ trigger.from_state.state if action == "" else action }}
- platform: state
https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-numbers-selects-and-sensors
According to this the state of trigger sensors is maintained across restarts
Why would mine go back to โNoneโ after reset?
Probably because your trigger doesn't filter out the invalid states
What would be the best way to do that?
Well, what does it appear as when you restart HA?
it just says "None"
Hello, I need a todays date in this format
date-month-year ex 29-12-2022
I was trying to read this https://www.home-assistant.io/docs/configuration/templating/#time
but I don't see any way to insert the todays date (29)
I'm not following the problem
now().strftime('insert format here')?
like this? {{ now().strftime("%d-%m-%Y") }}
I suspect so ๐
this part confused me:
but I don't see any way to insert the todays date (29)
but anyway...
Indeed, it seems very strange.
thanks, where is the documentation for strftime?
Probably it would work here if you add this to your trigger:
not_from:
- unavailable
- unknown
like this:```
- trigger:
- platform: state
entity_id: sensor.living_room_tap_switch_action
not_from:- unavailable
- unknown
sensor:
- name: Living Room Tap Switch
icon: hue:tap
state: >
{% set action = states('sensor.living_room_tap_switch_action') %}
{{ trigger.from_state.state if action == "" else action }}```
- platform: state
Just checked and I think that worked. That was much easier! haha
@marble jackal similar question that this resolution I recall being a part that can fix it, I do this with my dashboard https://tinyurl.com/2o3ze5f7 showing secondary_info: last-changed on the card, how can I make either all my entities or just some use what you put to not reset the state if restarts ect?
example of the yaml entity: light.living_room toggle: 'on' type: custom:slider-entity-row icon: mdi:sofa secondary_info: last-changed
I guess this fits in here. I got my automation and it throws the following error: I dont really find anything to fix it. It throws the following error:
In 'condition':
In 'template' condition: TypeError: is_state() takes 3 positional arguments but 4 were given```
https://hastebin.com/ugomozulep.yaml
What is this supposed to be doing?
value_template: "{{ is_state('sensor.room_brightness_' ~ trigger.entity_id.split('_')[2], 'below', 50) }}"
use the trigger to check the brightness in the room that triggered and give true if the state is below 50
I would try
value_template: >
{% set brightness = trigger.entity_id | replace('binary_sensor.motion', 'sensor.room_brightness'') %}
{{ is_state(brightness, '<', 50) }}"
(Untested as I'm on mobile.)
That, with the fixed quotes still throws the same error somehow..
Then perhaps:
value_template: >
{% set brightness = trigger.entity_id | replace('binary_sensor.motion', 'sensor.room_brightness') %}
{{ states(brightness) | int < 50 }}"
(Untested as I'm on mobile.)
I have a template that show all devices where at least one entity state is unavailable or unknown. https://hatebin.com/gqqvflvlot
That works fine, but since a few devices tend to be unavailable for only a few seconds (android_tv for exemple) clutter the result, I would now like to only fetch the ones with that have been unavailable/unknown for at least 2 minutes.
Suggestions how?
That seems to have done it. Had to fix some more stuff but now it works. For the ones who are interested: https://hastebin.com/ehoqonanow.yaml
{% for device in states | selectattr('state', 'in', ['unavailable', 'unknown']) %}
{% set elapsed_time = as_timestamp(now()) - as_timestamp(device.last_changed) %}
{% if elapsed_time >= 120 %}
{% set ns.items = ns.items + [ device_attr(device.entity_id | device_id, 'name') ] %}
{% endif %}
{%- endfor %}
{{ ns.items }}```
Try this.. Not sure though
Any solution will require that the card supports templates, does this one support them?
Use last_changed and check if that was more than 2 minutes ago
happy to use any card that does
entity: light.living_room
name: Living Room Light
icon: mdi:sofa
secondary_info: last-changed
state_filter:
- 'unavailable'
for example but I spose entity doesn't support sendary_info I think
You can't just throw any keys into any card, check what the card supports.
https://community.home-assistant.io/t/retain-last-state-change-data-of-a-sensor-after-reboot/125148/24 is spose the thing to vote for ๐
Depending on your sensor that might not be possible. But one reason I use #zigbee-archived and specifically Z2M for my temperature sensors
Don't think that will happen, as there is a state change (from an unknown state to an normal state).
There are method to store it in a sensor, but then you need templates to get it in your card.
allow to ignore unknown state?
https://tinyurl.com/2g4bsrxx is what lot of people have and reboots reset it all
trigger:
- platform: event
event_type: esphome.switch
event_data: {}
condition:
- "{{ trigger.event.data.hostname.startswith('s-') }}"
action:
- service: light.toggle
data_template:
entity_id: light.{{ trigger.event.data.device }}```
I'm being told that `data_template` has long been depreciated, but random google hit says `data` will not work if you use a template. What would be the proper method of calling the entity provided by the trigger template?
Don't look randomly on google, check the docs
Is this an automation or a trigger template?
automation
As the docs page specifies that it takes the same parameters as light turn on, update your toggle with that
Not really worried about brightness/color/effects yet, if I can toggle state I'll be happy with the progress. It looks like I can just get rid of data_template completely?
action:
- service: light.toggle
target:
entity_id: light.{{ trigger.event.data.device }}```
Probably, assuming that device exists ๐
ahh, now I see the use case for data in the example, as opposed to data_template. I was using it incorrectly from the start
these are esphome devices, I'm using standardized naming to make sure the device exists ๐ . I'll probably create a blueprint to create the light group if a new switch is added, but I'd really love to stumble on a method of handling it all without user interaction
@undone jungle I converted your message into a file since it's above 15 lines :+1:
in short is this correct:
state: >-
{% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('binary_sensor.fan_operational', 'on') %}
{% set strumienN = states('sensor.air_supply_flow') | float %}
{% set tcz = states('sensor.incoming_air_temperature') | float %}
{% set tn = states('sensor.room_supply_temperature') | float %}
{% if states('sensor.incoming_air_temperature')|float < states('sensor.air_supply_flow')|float %}
{{ ((((tn - tcz) * strumienN * 1200) / 3600)|float) | round(2, default=0) }}
{% else %}
{{ (((((tn - tcz) * strumienN * 1200) / 3600) * -1)|float) | round(2, default=0) }}
{% endif %}
{% else %}
0
{% endif %}
Or should there be another if resulting in :
{% if is_state('binary_sensor.ventilation_bypass', 'off') and **if** is_state('binary_sensor.fan_operational', 'on') %}
Hmm, apparently the template won't convert spaces to underscored automatically. I'll have to re-think this
| slugify
perfect! thanks
{% for chore in state_attr('sensor.grocy_chores','chores') if
chore.next_execution_assigned_to_user_id == 3 and
strptime(chore.next_estimated_execution_time,'%Y-%m-%dT%H:%M:%S')|as_local
<= today_at('23:59:59') and (chore.next_execution_assigned_to_user_id, '3')
%}{{chore.name}}{% else %} No chores for you today! {% endfor %}
Need a carriage return after chore.name and nothing I've tried has provided that. tried \n and <br> and always showing results running into themselves
Kitchen - Wipe CountersKitchen - Clean stove top
Should read:
Kitchen - Wipe Counters
Kitchen - Clean stove top
Just a wild guess, but maybe pipe it into a list?
%}{{chore.name | list}}{% else %} No chores for you today! {% endfor %}
Ah, let me give that a try
Is that all on one line? You should be able to add a line break inside the template, before and after {{chore.name}}
I get the principle, and I have another template that evaluates if a sensor last changed for more than 10 minutes ago.
https://hatebin.com/zgodqpmbkq
..but I don't understand how to combine them. Any suggestions or examples to get me started?
{{ chore.name ~'\n' }} should also work
['K', 'i', 't', 'c', 'h', 'e', 'n', ' ', '-', ' ', 'W', 'i', 'p', 'e', ' ', 'C', 'o', 'u', 'n', 't', 'e', 'r', 's']['K', 'i', 't', 'c', 'h', 'e', 'n', ' ', '-', ' ', 'C', 'l', 'e', 'a', 'n', ' ', 's', 't', 'o', 'v', 'e', ' ', 't', 'o', 'p']
Hahaha
It's not a bug, it's an undocumented feature
Thanks @marble jackal That did the trick! and thanks to you all
Just to be sure, this template is correct?
template:
- sensor:
- name: "woonkamer_total_covers_closed"
state: >
{{ expand(states.cover.woonkamer_covers) | selectattr('attributes.current_position', 'eq', 0) | list | count | int }}
- name: "woonkamer_total_covers_closed"
I have problems in the frontend that when the sensor is zero (it gives really zero in the developer tools) it doesn't show it.
Any ideas??
works fine here, with the exact same code as you are using I get a sensor which shows 0 as it's state.
However, I think you want to use : {{ expand('cover.woonkamer_covers') | selectattr('attributes.current_position', 'eq', 0) | list | count | int }}
The first one is correct. Since you ask, I assume it doesn't work, but then it's probably in the rest of the conditions. If I replace your entities with values like below, it returns -0.67. {% if 1==1 and 2==2 %} {% set strumienN = 1 | float %} {% set tcz = 2 | float %} {% set tn = 4 | float %} {% if tcz < strumienN %} {{ ((((tn - tcz) * strumienN * 1200) / 3600)|float) | round(2, default=0) }} {% else %} {{ (((((tn - tcz) * strumienN * 1200) / 3600) * -1)|float) | round(2, default=0) }} {% endif %} {% else %} 0 {% endif %}
Okay, yes also without the states. I get the same result in the developer tools. So I think it is a bug in the frontend (mushroom: chip template)
It did work after I corrected some spacing. Thank you for checking!!!
But you are creating a template sensor here? What is the state of that sensor?
While I have you, I have one follow up. Since this sensor is recording recovered energy, I wouldn't want it to return a 0 when the HVAC is off, since it will 'dilute' the value if pulled into a mean later on.
Is it OK to follow the else with unknown instead
Or will this cause issue when trying to use it for later calculations, since it's a non-numerical value
Would giving it a unavailable instead be a better idea?
Good example is here:
- name: "Ventilation energy efficiency"
unique_id: "recu_energy_efficiency"
icon: "mdi:percent"
unit_of_measurement: "%"
state: >-
{% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('binary_sensor.fan_operational', 'on') %}
{% set t1 = states('sensor.incoming_air_temperature') | float %}
{% set t2 = states('sensor.room_supply_temperature') | float %}
{% set t3 = states('sensor.room_exhaust_temperature') | float %}
{{ (((t2 - t1) / (t3 - t1)) * 100|float) | round(2, default=0) }}
{% else %}
0
{% endif %}
I don't want the efficiency to drop to zero when the HVAC is off
It should become unknown since the energy exchange simply doesn't happen, so we don't know what the value is at the time on the HVAC unit.
0
Well, then it is indeed an issue with the card. What is de code of the card
type: custom:mushroom-chips-card
chips:
- type: template
content: >-
{{ states('sensor.woonkamer_total_covers_closed') }}
and that also returns 0 in devtools > templates?
What if you just use the template for the template sensor in you chip?
yes
Well, it all depends how you want to use the result. If you don't use the else, clause at all, the result will be nothing (or maybe none).
As it is now (0) is fine is you want to use it for calculations. Or 1 if that suits you better. But if it is only for show in the GUI, maybe "Not operational" is a better choice. You decide ๐
@plush willow I converted your message into a file since it's above 15 lines :+1:
Maybe I could use null?
You can use whatever you want, you decide. Personally, I avoid unknown and unavailable since that often indicate that something's wrong.
Ahh, fair point. I'd like the GUI to show.
If I remove the else all together, I will probably see nothing there.
Need to play with it a little.
Maybe using the template editor in the Developer tool will be a good idea
Always
@undone jungle I converted your message into a file since it's above 15 lines :+1:
hey guys. I'm new and discovering Discord and found HA is here. Great. Maybe someone is able to help me with a sensor issue?
I monitor RPi's and as soon as it goes offline, I want the "last seen" date/time to be there. Date/time is one of the attr of the MQTT message.
So how to create a "last seen" sensor with date/time which is updated only when the RPi is Up?
Though, it's still not perfect....
Brainstorming... I have a working event trigger automation that listens for switch entities and activates light.{{entity}}.
What I'd like to do instead is return a list of devices. Effectively the same functionality as a light group, but this way I don't have to create a matching light group for each of my switches
"return"?
or "activate"? (which I guess means turn on/off)
you want some way to correlate a switch with a set of lights?
Is the Availability:False the correct output when availability is used in the template?
@undone jungle I converted your message into a file since it's above 15 lines :+1:
What am I doing wrong here? Shouldn't it return unavailable?
I am wondering if the statement after availability: should be in parentheses?
you need to surround the template in quotes
@inner mesa Here's an partial automation example that does not work, but I can't understand what the error not a valid value for dictionary value means.
action:
- service: light.toggle
target:
entity_id: {{ states.light | selectattr('entity_id', 'search', trigger.event.data.device | slugify ) | map(attribute='entity_id') | list }}```
oh, QUOTES
I was reading quote and thinking brace
I'm reading, but I'm having a hard time comprehending
this bit:
You must surround single-line templates with double quotes (") or single quotes (').
so I guess step one: nomenclature. What exactly is considered the template in that line? Just the 'trigger.event.data.device' ? or the entire line from opening double-brace to closing double-brace?
everything in '{{ }}'
that's Jinja
first link in the channel topic
Also, without knowing what your event structure looks like, I can't tell if this is really doing what you expect: selectattr('entity_id', 'search', trigger.event.data.device | slugify ).
I suspect not, but ๐คท
{{ trigger.event.data.device | slugify }} returns the event.data.device tag for the entity that called the event. In this case, for simplicity, it returns the string 'diningroom'
so my logic is to search all entity_ids for 'diningroom', and return a list of matches
ok
Hey everyone! {{input_datetime.last_irobot_run<now() - timedelta( hours = 12 )}}
First time using template, I'm getting this error: UndefinedError: 'input_datetime' is undefined. What am I doing wrong?
That entity id exists and has a value
I hope that question will not fall under 'you didn't read the documentation right', since I did look for it:
What is the risk of having several template sensors under one - sensor: headers? They all seem to work just fine.
@undone jungle I converted your message into a file since it's above 15 lines :+1:
{{ states('input_datetime.date_test')|as_datetime|as_local < now() - timedelta( hours = 12 )}}
no problem at all
that's what I do
Is that the answer to my question?
yes
OK, any reason why a sensor header for each vs. one for all is beneficial?
no
Beyond code beautification...
Thanks Rob!
presumably it's that way because you can provide an optional trigger and those blocks can be different, but there's no problem repeating the sensor: header other than extra typing
how is this template invalid? it's part of a blueprint's action
- if:
condition: numeric_state
entity_id: !input main_light
attribute: brightness
above: "{{ complimenting_brightness * 2.55 }}"```
complimenting_brightness is equivalent to `10`, and is being setup as a template var from a blueprint's input correctly, but the blueprint is erroring out saying `above` is `None`
Thanks, super helpful! Now trying to use value_template in numeric-state-condition to multiply the brightness attribute by 2.55. Have not been successful in fixing the errors yet.
See YAML code sample and value of state @: https://dpaste.org/sR9Q0
Problem is state.state appears to be referring to the on/off status of the light, and state.brightness claims it doesn't exist - despite it appearing in the value of state. (The value of state in the dpaste comes from {{ state }}.)
Not sure if this question is for that channel, but I'll give it a try:
https://i.imgur.com/MT3mIeB.png
When a templeted sensors becomes unavailable, it continues to assume the last known value and when used for any calculations, I think it will return this value back for these calculations.
In some cases though sensors stop plotting the value all together (unknown), for example MQTT sensors do that.
Is it possible to use a similar mechanism as availability: to produce an unknown value when certain conditions are not met?
Example of a Wifi sensor on ESP module, losing connection and thus not plotting the last Wifi signal:
https://i.imgur.com/wdMxxr5.png
brightness is an attribute, so you would use state.attributes.brightness
quick one..
{{ states('sensor.octopi_model') ,states('sensor.octopi_model')}}
gives output with braces -> ('RPi 3 Model B+r1.3', 'RPi 3 Model B+r1.3')
How to remove these?
Someone else may chime in, but I just tested a few things and to me it looks like an oddity in the frontend graph for unavailable values. If you get the standard bar chart, there is an empty block and shows it as unavailable. You'll also get unavailable back during any evals of the state, as well.
OK! I am sorry for not knowing how to test it myself, but will any algebraic operation on this block return an error/dev-by-zero/etc. when the sensor becomes available again?
My concern is that it will return a value of an extrapolation between the last known value and the one that succeeded it when the sensor return to life.
Something down the line of:
- it was 10
- it died for some time
- it returned as 1000
so the operation on the time between the 10 and 1000 return a value of a y=ax+b slope.
While it should return some form of error since there is no data for this block of time..
What do you have using it? If a template is using it, you can define a default value, for example {{ 100 / states('sensor.unavail_sensor') | int(-5) }} will use -5 as the denominator if the sensor has a non-integer value.
The comma is turning it into a tuple, represented by the parentheses. If you just want a space separating them, {{ [states('sensor.octopi_model') , states('sensor.octopi_model')]|join(' ') }}
this errors in the template., but usefull food for thought, learning HA. I fiddled some more and found {{ states('sensor.octopi_model') }} ({{states('sensor.octopi_model')}})
to be working as I wanted it: RPi 3 Model B+r1.3 (RPi 3 Model B+r1.3)
Thx!!
ok
I was considering a broader aspect of different sensors, but currently working on a simple sensor measuring power recovered by my HVAC unit, which is then used to integrate it to energy and collected by a utility meter.
Also, I am not sure how would this block be added to a standard numerical sensor. Do you have an example where you are using it?
This might be related https://github.com/home-assistant/frontend/issues/14331
But, I guess the point is from what I see is that how an unavailable state is displayed/interpreted depends on who's reading it. The frontend decides to sometimes interpolate or maintain the existing value, but something like the energy component likely handles unavailable in a different manner.
This is an absolute hack, but it works!
action:
- service: light.toggle
target:
entity_id: |-
{{ states | selectattr('entity_id','gt','light.dining') | selectattr('entity_id','lt','light.diningzzz') | map(attribute='entity_id') | list }}
Yup, seems like what you described. In some places it's unavailable and in some interpolated.
How about? {{ states | selectattr('entity_id','match','^light.dining') | map(attribute='entity_id') | list }}
Well, hell. I didn't think about regex
We try not to ๐
aand I got the single-line quoting wrong again
{{ states | selectattr('entity_id','match','^light.{{ trigger.event.data.device | slugify }}') | map(attribute='entity_id') | list }}
gack. now you're nesting templates
{{ states | selectattr('entity_id','match','^light.' + trigger.event.data.device | slugify) | map(attribute='entity_id') | list }} should work
might be better looking if you compute the match outside
with a variable: entry?
you can further optimize that like this:
{{ states.light | selectattr('object_id','match',trigger.event.data.device | slugify) | map(attribute='entity_id') | list }}
Somewhat new to templating, is there a more efficient/neater way to do this? It does work as-is, but I feel like I may have made it overly complicated
{{ expand('group.lights_all') | rejectattr('entity_id', 'in',
expand('light.bedside') | map(attribute='entity_id') | list) |
map(attribute='entity_id') | list }}
For context, group.lights_all is a YAML defined group of several switches and lights, light.bedside is a light group created via the UI consisting of 2 lights. The goal is to get a list of entity IDs, excluding the bedside ones, that I can pass to the light.turn_off service
yes, that can be greatly simplified
{{ state_attr('group.fr', 'entity_id')|reject('in', state_attr('group.fr', 'entity_id'))|list }}
that excludes everything in the group, but hopefully you get the idea
object_id alone helps greatly. I honestly stopped looking after I found the first name-based field
Is there any way to specify the icons for the template:lock in the same way as template:cover?
I am using it for a simple buzzer style side gate, but it's only turning the icon red as opposed to using the animation
@undone jungle I converted your message into a file since it's above 15 lines :+1:
Here the template lock:
lock:
- platform: template
name: Side gate
value_template: "{{ is_state('switch.side_gate', 'off') }}"
unlock:
service: switch.turn_on
target:
entity_id: switch.side_gate
lock:
service: switch.turn_off
target:
entity_id: switch.side_gate
The documentation doesn't indicate it being possible, but just thought I'd ask:
https://www.home-assistant.io/integrations/lock.template/
I guess not...
https://i.imgur.com/5BMpUNU.png
aha, thanks. I started out thinking reject() was the way to go based on the Jinja docs, but I couldn't find an example of how to use it or what tests were available there. Is there a page I missed that has the 'in', 'eq', etc?
The closest example I could find in the HA docs was just select('is_state', 'on')
Is is possible to use multiple value.split calls to pull the information before and after a symbol?
Current yaml is
- unique_id: milk_price
name: Milk Price
select: "data.kds-Price:nth-child(2)"
value_template: '{{ (value.split(":")[1]) }}'```
and I'm trying to pull the price which is listed in `value:"x.xx"` but not the quotation marks.
pfft, had to search for that
anyway, they're in the docs in the first link in the channel topic
if the string to parse is really 'value:"x.xx"', then {{ 'value:"x.xx"'.split('"')[1] }}
Do you need single quotes around double quotes?
in the split()?
you need to provide a character/string to split on, and you do that by surrounding it in quotes
and if the character is in fact a " , I'd need .split(""")?
my issue must be with the select then.
or the output isn't really what you said it was
Most likely, as the sensor just shows unavailable after calling the update service.
Is there a way to make a script to cycle through different wled effects when it is run?
There's a workaround script here that implements select.select_next.
https://community.home-assistant.io/t/support-select-select-next-and-select-select-previous/333090/5
Any ideas anyone??
I need a template for a calendar event, that identifies whether it's the day of or day after a specific calendar event. Where can I find some examples?
What is the use case?
series of repeating events in local calendar. need a trigger to identify when to send a tts notification to Alexa
You're still not really providing an example that someone can really envision ๐
the visual editor for automations doesn't offer much for calendar triggers
it lets you trigger based off of IF an event is active...but not choose which event is active
Did you look at the second example here?
https://www.home-assistant.io/integrations/calendar/#automation-recipes
yes... that, again, triggers if there is an event... which does NOT specify WHICH event
Ahem, did you read the WHOLE example?
The condition explicitly looks at which calendar title it was ๐
okay, that's my question that I am asking here - it's not clear where exactly that is
RTFM - got it, ty
It expects you to understand enough of the automation syntax to see the condition, and then keep reading ๐
Hi, is there a nice way to see when (time/date) a script was last executed? I'd like to have this to calculate other stuff from it...
Yup, it shows in the UI for starters
True, but if I need it in a script/automation?
attribute: last_triggered
You can see all the attributes for an entity in the Developer Tools menu
{{ state_attr('automation.back_bedroom_button', 'last_triggered' }}
Very nice, thank you! ๐
@silent seal, would you mind weighing in on this?
I'm not sure why you're tagging me, but simply put: if it's not in the docs then it's not supported.
My apologies! You were the mod 'on duty' dealing out advice, so I thought I'd ask, since no one responded for a few hours.
- HAOS
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
I apologize if I broke any unspoken rules.
You can (should) always run that โ๏ธ anyway
Is that meant for me?
I am not sure how it relates? Would you mind expanding?
The config check is required to reboot HAOS so it's definitely being run on my end.
The config check will tell you if your configuration is correct or not. If you have something invalid in it, it will let you know
Absolutely, but it's a positive check of the used syntax, you cannot check what you didn't type correctly this way.
It would complain about icon_template not being supported for that
If there is no clear syntax outlined in the docs there may be 'workarounds' how people do it, or 10 different ways to skin the can as is often the case in templates.
It did already in the VSC, as indicated
That's not the config check though
VSC shouldn't be your source of truth. It's not always accurate
I understand, but if it already complained there, I assumed it would elsewhere
Not necessarily. It sometimes complains about stuff that's valid
This said, knowing this most likely will not work, I was wondering if there is a workaround. In this case it does complain in the config check, so it's kind of a moot point, but I take the criticism not to always trust it.
To clarify, the config check is accurate, but VSC is not necessarily accurate
Yes, I did get that.
But as I said, in this case both indicated the same thing, so we are on the same page. In the future, I'll make sure to check both, though it's not really progressing the conversation in this particular situation. ๐
It's kind of a long way of arriving at - NO, there is no way to specify the icons.
tbh I'd say disregard VSC and only pay attention to the docs and the config check
I'll consider your advice - thank you!
I have a question:
I have an input NUMBER helper "input_number.minutes_after_motion" that I'd like to set as a duration condition.
But I keep getting the error: ***"Message malformed: expected float for dictionary value @ data['for']['minutes']" when I do this: ***
type: no_motion
platform: device
device_id: 7b98fc28dccab869717ad5a82959aa78
entity_id: binary_sensor.hue_motion_sensor_entre_motion
domain: binary_sensor
for:
minutes: {{ input_number.minutes_after_motion | float }}
Can anyone help me?
Try surrounding the entire template with double quotes
If you want the state, you'll need states('input_number.etcetc')
for:
minutes: {{ states('input_number.minutter_etter_bevegelse') | float }}
Same error message ๐ฆ
You still need double quotes around the whole thing
Same message, with double quotes, single quotes and no quotes
maybe the for.minutes does not accept automation? - it accepts the value 5 without any issues
Device triggers don't like templates - use a state trigger
oh!
for the hue motion sensor, do I then ask the sensor attribute 'motion_valid' or just go with 'off' for binary_sensor.hue_motion_sensor_entre when I want to check for no motion?
Simple state trigger on that entity
platform: state
entity_id: binary_sensor.hue_motion_sensor_entre_motion
from: 'On'
to: 'Off'
for:
minutes: '{{ states(''input_number.minutter_etter_bevegelse'') | int }}'
Well, it accepts it, hopefully it'll work too ๐
It won't
And it didn't ๐
On isn't the actual state, and neither is Off
show your state developer tools
AAH, there they are!!
i don't understand what's going on here. with the expression "{{ color == '-1' }}" when color has the value -1 as a string it evaluates to false. if i do "{{ '-1' in color }}" it evaluates to true. if i cast both sides to an int and do the comparison it evaluates to true. is there a .equals method like in java that i need to use to compare the values so that a more correct comparison is done?
It's motion_detected and clear right? ๐
Mine is showing as 'off' currently
Where does this color variable come from, and what is the value of this variable
binary_sensors are either or on off
Or unavailable or unknown
Or badly programmed ๐
platform: state
entity_id: binary_sensor.hue_motion_sensor_entre_motion
from: 'on'
to: 'off'
for:
minutes: '{{ states(''input_number.minutter_etter_bevegelse'') | int }}'
So this should be correct then ๐
it's declared as a field in a script with a select selector and a list of options with string keys as the dictionary. it is a string. i can see this if i do color.anything because the error message complains that a string doesn't have an anything. as i mentioned the value is -1 which is further proved by the secondo and third comparisons i made.
this post shows a similar issue. https://community.home-assistant.io/t/comparing-strings-in-automation/67709 in yaml do single quotes do something weird to strings? like create a static version that doesn't unbox or something?
@acoustic inlet I converted your message into a file since it's above 15 lines :+1:
weird... apparently in jinja i have to cast both sides to strings. why is this?
they are already strings
oh, well. i guess i don't care. it's jinja and in somebody's eyes '-1' does not have a type
thank you everyone
Sure -1 can have a type
{{ "-1" is string }} True
{{ -1 is string }} False
{{ -1 is integer }} True
{{ [-1] is string }} False
unrelated new question, i am creating a template light to fix some weirdness in a firmware of a zwave device. the zwave device only has a "brightness" state attribute when the light is on and the brightness attribute is not defined when the device is off. maybe this is normal. that's not important to the question. i have a level_template like this: level_template: "{{ state_attr('light.entityofthething', 'brightness')|int }}" which works fine when the device is on but results in an evaluation error in jinja when the device is off because i have no default. any idea if there will be ill effects if i provide default(0)|int so that level is always defined? are there parts of home assistant that will consider the light to be on if it has a value or any weird gotchas like that?
ah, i found some help here. https://community.home-assistant.io/t/updating-templates-with-the-new-default-values-in-2021-10-x/346198
Hi all, why is this template binary sensor not working?
template:
- binary_sensor:
- name: "Badezimmerlรผfter_State"
unique_id: BadezimmerluefterState
state: >
{% if states('sensor.lufterbadsupply_power') | float <= 0.6 %}
{{off}}
{% else %}
{{on}}
{% endif %}
- name: "Badezimmerlรผfter_State"
I always get 'UndefinedError: 'on' is undefined' as error
fixed it --> instead of off/on I had to use false/true
It would be helpful if you shared the entire code instead of just a snippet
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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 could use just this as state template {{ states('sensor.lufterbadsupply_power') | float <= 0.6 }}
That will return true or false (or will run in error when the source sensor is not available, since you did not provide a default)
Hi guys, how can I get this to do what I need please? https://paste.debian.net/hidden/c8dccb18/
I have the time of the last triggered, and want to add a random time (delta) to that. It is added twice on purpose to compensate for the transition time (light register as off despite still emitting light)
I have been testing in dev-tools a lot, but (as of yet) failed to get it right
last_triggered is already a datetime, but for some reason that doesn't work in devtools
Ok. Perhaps converting to timestamps would work better?
Also you were adding the timedelta to a string at the end
{% set delta = timedelta(minutes=range(1,9)|random * 2) %}
{{ (state_attr('script.lights_off', 'last_triggered') | as_local + delta).strftime('%Y-%m-%d %H:%M:%S') }}
This will not work in devtools, but it will in the automation
Where are you using this BTW? In the same automation?
It is kind of cross automations, used to calculate other scripts to run after lights go out
I am setting a datetime helper, which then is read by other scripts
Why are you converting it to a string then? The input_datetime service call accepts a datetime
{% set delta = timedelta(minutes=range(1,9)|random * 2) %}
{{ state_attr('script.lights_off', 'last_triggered') | as_local + delta }}
Good question. I was trying back and forth and ended up with that
This looks much better, thanks for the help! ๐
I'm currently learning templating and was wondering if there is currently a source or list of all templating functions like is_state?
Can someone give an idea for a template? 4.186(80000[60-'sensor_state'])/1500= value
This is a good start: https://www.home-assistant.io/docs/configuration/templating/#states
Thx!
Like {{ 4.186*(80000*(60-states('sensor.your_sensor')|float))/1500 }}?
Yep, that's it. Thanks... My head was frying after some maths.
I'm following a youtube vid that has this code:
{% set output = namespace(sensors=[]) %}
{% for state in states.sensor | selectattr('attributes.device_class') %}
{{ state.name }}
{% endfor %}
But my output is:
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'
Any ideas what I'm missing?
{% set output = namespace(sensors=[]) %}
{% for state in states.sensor | selectattr('attributes.device_class', 'defined') %}
{{ state.name }}
{% endfor %}
Assuming there's more to that template? Otherwise... seems odd
Its just the beginning
The video is 11 months old, is it just out of date?
probably 10 months out of date
@obtuse zephyr I really appreciate all your help
Possibly ๐คทโโ๏ธ Or he's only got sensors that have a device class
Thx for that
Everyone's set up is different, you'll find that videos can be frustrating at times
Definitely a good idea to read through that templating doc, so even if you do check out videos, you can understand what might be going wrong and what options there are to fix
Will do
What if I want to filter for "battery"?
Maybe selectattr('attributes.device_class','eq','battery')
Hmm no
And if it was: 4.186(80000[60-'sensor_state'])/'sensor2_state'= value
Sorry, can't seem to get it right...
{{ 4.186*(80000*(60-states('sensor.your_sensor')|float))/states('sensor.your_other_sensor')|float }}
@obtuse zephyr What if I want to test for 'battery' in:
{% for state in states.sensor | selectattr('attributes.device_class', 'defined') %}
states.sensor | selectattr('attributes.battery', 'defined') ?
...or
|selectattr('attributes.device_class', 'eq', 'battery')
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'
Both?
{% for state in states.sensor | selectattr('attributes.device_class', 'eq', 'battery') %}
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'
Am I misunderstanding?
- sensor:
- name: Steam Online
state: >
{{ states.sensor | select('search', 'steamid_')
| selectattr('state', 'eq', 'Online') | list | count }}
Can't find the answer online but looking to get all state that DO NOT equal "online". Any ideas?
Yes, you are misunderstanding
The point is: you need to select for the attribute to be defined, then that it is what you want
2+2
@obtuse zephyr Suggestion does not come up with results
Are you looking for device_class: battery?
here
Then you need Rob's
{% for state in states.sensor | selectattr('attributes.device_class', 'defined') |selectattr('attributes.device_class', 'eq', 'battery')|list %}
thanks @obtuse zephyr another great page for my bookmarks ๐
Works and studying to learn.. Thx guys
You could also rejectattr instead of selectattr
Why was it important to check for "defined". Does this eliminate sensors that didn't have a "device_class" attribute?
That it does
Wish I could buy you guys some beers
In this tutorial is the following:
{% if 0 <= state.state | int(-1) %}
Is "unknown" considered "less than zero"?
It was used to remove unknown values
"unknown" (the string) will result in that evaluating to -1
which will make that "false"
Thx Rob.. This is all jinja-related stuff, right?
yes
If so I can attack that manual
Perfect
see the links in the channel topic
Will do!
What would be the best way to resolve: TemplateError('ZeroDivisionError: float division by zero') while processing template?
I've tried with availability_template, but no luck.
availability_template: "{{ states('sensor.2')|float != 0 }}"```
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
Please share the YAML of your template ๐
value_template: "{{ (4.186*(80000*(60-states('sensor.1')|float))/states('sensor.2')|float) | round(0) }}"
That's not the whole template sensor/config ๐
Also, sensor.1 is not the world's greatest name. I recommend sensor.bedroom_temperature, binary_sensor.bathroom_occupancy, etc. as names.
sensors:
time_heater_seconds:
value_template: "{{ (4.186*(80000*(60-states('sensor.shelly1pm_e8db84d807c5_temperature')|float))/states('sensor.heater_watts')|float) | round(0) }}"
#availability_template: "{{ states('sensor.heater_watts') not in ['0', 'unavailable', 'unknown', 'none'] }}"
availability_template: "{{ states('sensor.heater_watts')|float != 0 }}"```
That's using the old config, so I recommend looking at the new syntax as a side note ๐
You don't have any defaults for the floats.
Isn't the default float(0) ?
{{ (4.186*(80000*(60-states('sensor.shelly1pm_e8db84d807c5_temperature')|float(0)))/states('sensor.heater_watts')|float(0)) | round(0) }}
That might fix it.
No, if the sensor is outputting unavailable then it won't be parseable as a float.
I think I tried, just in case, but it didn't work. Let me check again...
template:
- sensor:
- name: "Time Heater Seconds"
unique_id: time_heater_seconds
state: >
{{ (4.186*(80000*(60-states('sensor.shelly1pm_e8db84d807c5_temperature')|float(0)))/states('sensor.heater_watts')|float(0)) | round(0) }}
availability: "{{ states('sensor.heater_watts') not in ['0', 'unavailable', 'unknown', 'none'] }}"
This would be the new syntax (I'm not 100% sure on the seconds, I'm going from memory there)
Oh, it did the trick!
I'm glad to hear it ๐
Thanks!
Definitely look at upgrading from the legacy format though. As per the docs it's not recommended: https://www.home-assistant.io/integrations/template/#legacy-binary-sensor-configuration-format
Yeah, will do.
Can I change a button icon on a card on the dash board from a script?
When you say change an icon, what is the button linked to?
A template sensor
Yeah, I just didn't know if I could update that icon from another method or if I have to include all of my icon logic in the template sensor
You can't change it another way, no
Appreciated!
I've been diving pretty hard in to templates and I'm currently reading up on jinja. I found a reference to the split function but I don't see it listed anywhere in the documentation. Am I missing it?
You mean the split config?
Here is now to split your configuration into multiple YAML files
No like providing a value and separating it into independent values with a delimiter
00:00:00 into three separate values using: as the delimiter
customer.date_of_birth.split('-') etc
Seems:
"A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple."
https://stackoverflow.com/questions/30515456/split-string-into-list-in-jinja
Lemmie tell you how easy stuff is to learn when it's not documented lol
I was about to tell you to look at the manual...but then ... wth... it is not documented ๐ '...no news for you
Lol
Jinja uses Python objects, so (in general) you can use any method supported by those objects
Thanks but .. 'any method'... this leaves the whole set of options wide open. For me (at least) as a slightly advanced / mediocrate jinja user, how would i know where to look and what method to be able to applu in jinja? Is thi sjust a question of eperience or is there readable guidance in this area.
Some of it is experience, but in general you can stick a template in
-> Templates and it will tell you the object type. Then you can search for Python methods that apply to that object
Unfortunately, that's not always a reliable way to identify the object type because it tells you the type of the output, and not necessarily the object that it came from. An example of that is {{ now() }}, where now() returns a datetimePython object, but the devtool displays it as a string, and tells you that it's a string
I have a sensor consisting of the product of two input numbers.
Calculation of Total Savings in โฌ
dogalgaz_fatura_accounting:
friendly_name: 'dogalgaz_fatura_hesaplama TL'
unit_of_measurement: 'โบ'
value_template: >-
{{ (float(states.input_number.dogalgaz_ilk_sayac.state) * float(states.input_number.dogalgaz_guncel_sayac.state) * 5.85) | round(3) }}
Even if I add a round, I have trouble rounding...
Result: 28.867.889,7 โบ
My desired outcome: 288โบ
OK, thanka and... I got a bit out of that ...
I can't tell what that number actually is based on the separators and groupings
What does it say in
-> Templates?
When used like that, round() acts on the fractional part of the value. It sounds like you want to round the whole part of the value, which I believe you can do by providing negative values to round()
{{ (float(states.input_number.dogalgaz_ilk_sayac.state) * float(states.input_number.dogalgaz_guncel_sayac.state) * 5.85) | round(0) }} This is the result when I do: 28867890
Yes we got rid of the decimal points, finally what are the chances to convert the value to ,288TL?
See last message
giving negative values did not work.
round(-3) value and this is the result: 28868000.0
so keep going
{{ 28867890|round(-5) }} -> 28900000
same with {{ 28867890.0|round(-5) }}
I kept going, I tested down to -60s. We got rid of the punctuation:) Now the result is good... Only how can I get it down to 3 digits, that's the problem now...
I don't know whether there's supposed to be a decimal part to this or not ,288TL
I don't know what the comma is there
divide it
{{ (28867890.0|round(-5))/100000 }} -> 289
or just {{ (28867890/100000)|int }}
-> 288
Should I create a template sensor again for this last code you wrote?
Actually, let me put it like this.
I don't need decimals.
I don't want to give you a headache, but the result I want to achieve... My goal is to calculate my natural gas bill. I have two input numbers. They are 4 digit input numbers. One represents the first meter and the other represents the current meter value... With the difference between the two, I find my natural gas consumption value, where an increase of the last value by one value corresponds to an increase of one cubic meter of natural gas. One cubic meter of natural gas is 5,85TL... These two input numbers
dogalgaz_fatura_accounting:
friendly_name: 'dogalgaz_fatura_hesaplama TL'
unit_of_measurement: 'โบ'
value_template: >-
{{ (float(states.input_number.dogalgaz_ilk_sayac.state) * float(states.input_number.dogalgaz_guncel_sayac.state) * 5.85) | round(3) }}
I multiply it by the sensor and the result will represent my natural gas bill for this month... But the result has both fractional and incorrect decimal values. Obviously, this does not satisfy me... With my Sonoff device that measures energy on the boiler, as the energy values increase, the input number will be updated and my natural gas bill will automatically appear on the screen... This is a stupid and simple method I think... If there is a simpler one you know you can direct me... Thank you for your answers...
Is there an easy way to permanently increase the size of the template editor in home assistant?
Another question, we assigned devices to a room but I don't see any reference to the rooms anywhere. Is there a way to see a list of all devices in each room?
You can get a list of the devices or entities in an area with area_devices('bedroom') or area_entities('bedroom')
https://www.home-assistant.io/docs/configuration/templating/#areas
Thx!
@floral blaze I converted your message into a file since it's above 15 lines :+1:
im trying to get this icon to 'boink' but for some reason it wont work out.
How do I get this to show XX:XX:XX format without the microseconds? Still a bit in the dark around the time manipulation with templates... ๐ณ ```
{{ now() - states.input_boolean.test.last_changed }}
You can make any time format you want with timestamp_custom()
Thx - I tried this, but it errors out on me, and I can seem to figure out why```
{{ now() - states.input_boolean.test.last_changed |timestamp_custom("%H:%M:%S") }}
It takes a UNIX timestamp, so you need to wrap your time in as_timestamp()
Do I wrap the whole thing or each one separately?```
{{ as_timestamp(now()) - as_timestamp(states.input_boolean.test.last_changed) |timestamp_custom("%H:%M:%S") }}
OR
{{ as_timestamp(now() - states.input_boolean.test.last_changed) |timestamp_custom("%H:%M:%S") }}
Both dont seem to work when testing them?
{{ (utcnow()|as_timestamp - states.input_boolean.dark.last_changed|as_timestamp)|timestamp_custom("%H:%M:%S") }}
(using my entities)
I know I can do now().timestamp() in a template to get the current timestamp, but what's the easiest way to get the timestamp without the time component (e.g. 00:00:00)?
but I need a timestamp of it
Ah I see, today_at returns a datetime I can convert, perfect!
didn't know about today_at, that's perfect, thanks
I am wanting to use this in a sensor as a type of stop watch - If I understand correctly now() will not update by itself, and I should rather use sensor.time, is that correct?
The sensor will be displayed on a dashboard showing the time which has elapsed.
now() updates every minute
aside from the docs, the template dev tool tells you that:
Is it possible to get an update every second?
Set a timer for the duration and display the timer
That was my initial thought, but there is no set time for the timer, as the duration is dynamic
I think I might have expressed myself wrongly - On the dashbord there is a button, once the button is pushed a "stopwatch" should appear showing the time elapsed in the XX:XX:XX format ticking up, until the stop button is pressed.
Stopwatches usually count up...
In any case, you can do what I've done before and do a brute force solution with an input_number and automation with a time_pattern trigger that increments it
Counting up is exactly what I am looking for ๐ Do you perhaps have an example of your brute force solution?
thx!
Anyone know card-mod? I want to change the background color of a gauge card based on the value of the entitiy.
type: gauge
entity: sensor.cell_1_voltage
card_mod:
style: |
ha-card {
--ha-card-background: teal;
color: var(--primary-color);
}
That gets me a teal background, but how can I change the color based on the value of the entitiy instead?
Hey, anyone know how to read out the state icon of an entity that doesnt have the icon as an attribute?
What am I doing wrong here pls? I have default defined ... TemplateError('ValueError: Template error: int got invalid input 'unavailable' when rendering template 'Hugo potลebuje vymฤnit hlavnรญ kartรกฤ (zbรฝvรก {{ ( states('sensor.roborock_vacuum_s5e_main_brush_left') | default(3600*100,True) | int / 3600 ) | round(1) }}h)' but no default was specified')
- trigger:
- platform: state
entity_id: sensor.office_desk_switch_action
not_from:
- unavailable
- unknown
sensor:
- name: Office Desk Switch
icon: hue:dimmer-switch
state: >
{% set action = states('sensor.office_desk_switch_action') %}
{{ trigger.from_state.state if action == "" else action }}
Can anyone tell me why this trigger sensor is "unavailable" after a restart?
As soon as I press a button on the dimmer switch it comes alive again
Well, this error message is quite clear. You are trying to convert unavailable to an integer, which is not possible
the default you applied doesn't work as you intented, because unavailable is a perfectly correct state, so the default will not be applied
use this instead (to apply the default value to the int filter):
{{ ( states('sensor.roborock_vacuum_s5e_main_brush_left') | int(360000) / 3600 ) | round(1) }}
what you could try is to create an automation with the same trigger. As action you can set a variable using the same template
you can then use the automation to debug the template sensor, as there are no traces for template sensors
How can I make a "cheapest_hour" sensor with a variable for "number of hours"?
So I can make an automation that says "Run the heater on the X cheapest hours"
(Later I want to make X depend on the out-door temperature.)
Not sure what you mean with number of hours here.
The code you provided seems to create 3 sensors which retrurn True or False
line 36 is wrong though, it had the platform: template part of the next sensor
I would suggest to create binary sensors instead of sensors returning true or false
I also think you can simplify your templates to this:
{%- set prices = state_attr('sensor.nordpool_kwh_se4_sek_2_10_025', 'raw_today') %}
{%- set ns = namespace(hour_price=[]) %}
{%- for i in range(0, 24) %}
{%- set ns.hour_price = ns.hour_price + [(i, prices[i]).value] %}
{%- endfor %}
{%- set sorted_hour_price = ns.hour_price | sort(attribute='1') %}
{{ now().hour in sorted_hour_price[:5] | map(attribute='0') | list }}
What you can do is create an input_number to set the number of hours you want to use (in the template above this is 5)
hey guys, i need a second pair of eyes on this one. Im trying to get this 'boink' animation to work on a specific state, it doesnt seem to work.
@floral blaze I converted your message into a file since it's above 15 lines :+1:
Ok.
So first i make an "input_number" that depends on the outside temperature.
Then I want to say:
Set the cheapest_hours to "true" for
{{ now().hour in sorted_hour_price[:"input_number"] | map(attribute='0') | list }}
almost ๐
template:
- binary_sensor:
- name: Cheapest Hours
unique_id: binary_sensor_cheapest_hours
state: >
{{ now().hour in this.attributes.get('cheapest_hours', []) }}
attributes:
hours_used: "{{ states('input_number.hours_to_check') | int(0) }}"
cheapest_hours: >
{%- set prices = state_attr('sensor.nordpool_kwh_se4_sek_2_10_025', 'raw_today') %}
{%- set hours_to_check = this.attributes.get('hours_used', 0) %}
{%- set ns = namespace(hour_price=[]) %}
{%- for i in prices %}
{%- set ns.hour_price = ns.hour_price + [(loop.index0, i.value)] %}
{%- endfor %}
{{ (ns.hour_price | sort(attribute='1') | map(attribute='0') | list)[:hours_to_check] | sort }}
this gives you a binary_sensor which is on during the cheapest X hours (where X is based on input_number.hours_to_check)
it has an attribute cheapest_hours in which the cheapest X hours are shown
and it uses the new template sensor format (so don't place it in sensor.yaml, you can place this code direcptly in configuration.yaml, unless you already have template in there)
Wow. Tnx.
I will have a real look at this later.
and the input_number.hours_to_check is set thru an automation?
made some adjustments
it's set however you want
manually from your dashboard, once, or through an automation
why canยดt i put this in sensor.yaml?
I canยดt have both
template:
- binary_sensor:
and - platform: template
sensors:
in the same yaml-file?
because the new format is part of the template integration, and not the sensor integration
it's a whole new integration
and sensor.yaml has the code for the sensor integration
Ah.
I think I understand.
A big thx!
you can create a template.yaml though, and include that one as well from configuration.yaml
I made a last minor change to the code above
hi everyone, I am struggling setting a template up for a restful notification integration (https://www.home-assistant.io/integrations/notify.rest/).
The api of the chat platform I am trying to use takes a message and a target - as usual - but optionally it also takes a bunch of extra fields (ie icon_url) that I am trying to map/pass to the data field
it currently looks something like
- platform: rest
name: chat
resource: https://xxxxxxxxxxx/hooks/xxxxxxxxxxxxx
method: POST_JSON
target_param_name: channel
message_param_name: text
data:
icon_url: '{{ data.icon_url|default("") }}'
icon_emoji: '{{ data.icon_emoji|default("") }}'
seems like this is not the right way to pass a default value in the post message, since I am getting Template variable warning: 'None' has no attribute 'icon_url' when rendering '{{ data.icon_url }}'
My ideal goal would be to be able to send a message such as
service: notify.chat
data:
message: hello
or
service: notify.chat
data:
message: hello
data:
icon_url: 'whatever'
and have either of them work
@inner mesa well the integration says that it takes a template in the data field, so that's basically what I am trying to figure out, I have never done this so I am equally confused
yes, I was wrong. I haven't used that integration before
So how do I implement a template? I have one created but not sure how to actually install it.
?
what do you mean by "install"? You put what you mentioned in #general-archived in your configuration.yaml
Ok so I have to put it in the yaml, gotcha.
Huzzah it worked.
Thanks @inner mesa
So for each template do I just place them under the existing template: header?
Ok that is cool
Hello, I have an error message "key error" with the follonwing tempalte :
{% set entity = states.sensor.a52s_last_notification | selectattr("attributes.android.text*", "search", "avant pleine") | selectattr("attributes.android.text*", "search", "Bruit dรฉtectรฉ") | list %}
{% if entity | length > 0 %}
{% else %}
{{ entity[0].attributes.notifA52 }}: {{ entity[0].state }}
{% endif %}
Somebody could help me please ? thanks
You have nothing in the 'if' branch
But your issue is that you need |selectattr('attributes.android.text', 'defined')
hello, the empty if branchh is normal i don't want any action inthere
in don't understant the issue selectattr('attributes.android.text', 'defined')
Post your actual error, do not paraphrase it
in the dev tools tab envent i have : KeyError:
the problem is that you do nothing if entity actually contains data, and if it doesn't you try do do stuff on an empty list
{% if states.binary_sensor.pir_sensor_4.state == 'on' and ({{ as_timestamp(now()) | float }} - states.binary_sensor.pir_sensor_4.last_changed | float) < 900 %}
True
{% else %}
False
{% endif %}
in this sensor I get the error TemplateSyntaxError: expected token ':', got '}.
Gack
{{ is_state('binary_sensor.pir_sensor_4', 'on') and (now() - states.binary_sensor.pir_sensor_4.last_changed).seconds < 900 }}
yes it's the point : when sensor.a52s_last_notification contain some attributs beginning by android.text and containing "avant pleine" and "Bruit dรฉtectรฉ" I don't want the attribut bebinning by android.text be load in the entity. Dio you understant my template ?
I don't think you understand your template:
{% set list = [] %}
{% if list | length > 0 %}
{# do nothing #}
{% else %}
{{ list[0] }}
{% endif %}
This is basically what you are doing, which will never work, because your list will be empty when you want to work with it
it shouldn't not be empty if the attibut beggining by android.text doesn't not contain "bruit dรฉtectรฉ" or "avant pleine" ?
It won't be empty, but you built your template do it doesn't do anything when it's not empty
I don't know how to do that in that way
Btw, the key error is probably caused by the . in the attribute key
I think you want something like this
{% set entity = 'sensor.a52s_last_notification' %}
{% set last = state_attr(entity, 'android.text') %}
{% if 'Bruit dรฉtectรฉ' in last and 'avant pleine' in last %}
{{ state_attr(entity, 'notifA52') }}: {{ states(entity) }}
{% endif %}
Not sure about this notifA52 attribute though, took that from your template
I have an array of weather forecasting data. How can I select the entries that are tomorrow at 06:00 or 09:00 and then apply a test to the precipitation_probability to see if it's above or below a certain threshold?
[[{'datetime': '2023-01-03T00:00:00+00:00', 'condition': 'clear-night', 'precipitation_probability': 0, 'wind_bearing': 'SSE', 'temperature': 3.0, 'wind_speed': 11.27}, {'datetime': '2023-01-03T03:00:00+00:00', 'condition': 'cloudy', 'precipitation_probability': 7, 'wind_bearing': 'SE', 'temperature': 3.0, 'wind_speed': 14.48}, {'datetime': '2023-01-03T06:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 88, 'wind_bearing': 'SSE', 'temperature': 4.0, 'wind_speed': 25.75}, {'datetime': '2023-01-03T09:00:00+00:00', 'condition': 'cloudy', 'precipitation_probability': 37, 'wind_bearing': 'S', 'temperature': 6.0, 'wind_speed': 20.92}, {'datetime': '2023-01-03T12:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 85, 'wind_bearing': 'SSW', 'temperature': 8.0, 'wind_speed': 14.48}, {'datetime': '2023-01-03T15:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 89, 'wind_bearing': 'SSE', 'temperature': 8.0, 'wind_speed': 11.27}, {'datetime': '2023-01-03T18:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 92, 'wind_bearing': 'SSE', 'temperature': 9.0, 'wind_speed': 11.27}, {'datetime': '2023-01-03T21:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 92, 'wind_bearing': 'SSW', 'temperature': 10.0, 'wind_speed': 17.7},]
So far I've been able to get part of the way, extracting the corresponding datetiimes that match 06:00.
| selectattr('datetime', 'match', '^.*06:00')
| list
}}
{{ weather | selectattr('datetime', 'match', '^.*0(3|6):00') | map(attribute='precipitation_probability') | list }}
Only you'd probably want to use selectattr on the precipitation_probability with > to check if it's above a certain number
Thank you @silent seal
Is there a way I can only focus on those datetimes that match tomorrows date ?
you can do something like this:
{% set tomorrow_6 = (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() %}
{% set tomorrow_9 = (today_at('09:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() %}
{{ state_attr('weather.home', 'forecast')|selectattr('datetime', 'in', [tomorrow_6, tomorrow_9])|selectattr('precipitation_probability', 'gt', 0.5)|list }}
Yup
{% set tomorrow = (today_at('00:00') + timedelta(days=1)).strftime('%F') %}
{{ weather | selectattr('datetime', 'match', '^'~tomorrow) | selectattr('datetime', 'match', '^.*0(3|6):00') | map(attribute='precipitation_probability') | list }}
Thank you. @silent seal I'd been struggling to find out a way to do date additions. Big help!
Or do what Rob said, he's much better at templates than I am!
Thanks @inner mesa
mine's certainly more complicated and I'm not yet convinced that it's better. I hadn't thought about doing it with a regex
I think(?) I need template help for something that seems like it should be straight forward. I want to do something like this:
sequence:
- service: input_number.set_value
data: {value: "{{ sensor.ecobee_temperature }}"}
target:
entity_id: input_number.targettemp```
Where I essentially set an input_number helper's value to the current temperature from a sensor? But I don't quite understand how to structure it from the documentation.
your indentation is all over the place there
alias: Set Current Temp
sequence:
- service: input_number.set_value
data:
value: "{{ states('sensor.ecobee_temperature') }}"
target:
entity_id: input_number.targettemp
There's a big section on how to retrieve a state in the docs
and the rest of that page
apologies, the translation out of the yaml view to discord code wasn't a clean paste process lol. I'll take a look, thank you.
they have an example in the docs, too:
automation:
- alias: "Set temp slider"
trigger:
platform: mqtt
topic: "setTemperature"
action:
service: input_number.set_value
target:
entity_id: input_number.target_temp
data:
value: "{{ trigger.payload }}"
That's exactly the one I was trying to use as a template
but you had this:
data: {value: "{{ sensor.ecobee_temperature }}"}
doesn't look like that
anyway, use what I provided and review the link above
it was my best guess going from a completely unrelated MQTT "trigger.payload"
This worked, thank you very much.
I followed the docs but I still having troubles to get it working
{% set tarief_per_kwh = 0.36 %}
{% set kwh = sensorwaarde_per_uur / 1000 %}
{% set kosten = kwh | int * tarief_per_kwh %}
{% set kosten_afgerond = kosten | round(2) %}
De kosten zijn {{ kosten_afgerond }} EUR.
TypeError: unsupported operand type(s) for /: 'str' and 'int'
What am I not seeing?
{% set sensorwaarde_per_uur = states.sensor.met_vermogen_per_uur.attributes.last_period | float %}
its a string right now
also {% set sensorwaarde_per_uur = state_attr('sensor.met_vermogen_per_uur','last_period') | float %}
Don't access states directly if you don't have to
Oke still learning but thanks
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
This may be useful while you're learning things ๐
Ahhh thx @silent seal
I'm a bit surprised why they didn't convert the value in the last_period attribute to a number already, as that is allowed in an attribute.
Hi guys. Had some help with this the other day but found out yesterday that it did in fact not work as intended after all. I need to set a simple datetime helper, but it fails in the calculation. Dev-tools thinks not what the interpreter does... Any ideas please? https://paste.debian.net/hidden/f8c1a74d/
Well, how can that be changed in a good way then? I have two sets of minutes from other variables...
No sorry for that. The whole thing is huge
You've only said 'fails the calculation'
Anyway,
I would also put |as_datetime before |as_local
Maybe I was confusing, but meant the error: TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'str'. So to be precise a data type mismatch
In front of ((state_attr('script.lights_off', 'last_triggered') or like | as_datetime | as_local The latter did not check out in dev-tools...
as_datetime converts a string to a datetime object. as_local attaches your local timezone to your datetime. So the only option is | as_datetime | as_local
Ok thanks, will try with that
Well, it gave an other error, so progress ๐ Error executing script. Invalid data for call_service at pos 3: Invalid datetime specified: ((state_attr('script.lights_off', 'last_triggered') | as_datetime | as_local) + (timedelta(minutes=3) + timedelta(minutes=7))).strftime('%Y-%m-%d %H:%M:%S') for dictionary value @ data['datetime']
you don't need the strftime() at all - you can just pass the datetime object
I added that to format the output for display purpose, but can remove it if it helps this
you have to remove it
the error is telling you it wants a datetime
you're changing it to a string
when you format it
as I recall, if you provide a datetime, it just uses it. otherwise, it tries to convert the string to a datetime
seems like "%Y-%m-%d %H:%M:%S" should work, but only if the value you're passing in is valid
well, then his issue is simpler than that
he's not making it a template
i.e. {{ and }} are missing
Hm. that is obviously not great... Thanks for pointing that out. Will change into a template and retry
that would have been clear if the "template" had been tested in the dev tool
I saw the "((" at the beginning and was confused by it ๐
Seems I have tested with {{}} in dev tools, just didn't copy them into the script ๐ฆ
Make sure you wrap it in quotes or use multiline yaml notation
More data type issues? {{ state_attr('script.lights_off', 'last_triggered') | as_datetime | as_local }} reders error TypeError: float() argument must be a string or a real number, not 'datetime.datetime'
looks like it's already a datetime object, so now back to your original template with just |as_local
|as_datetime gives that nonsense error if it's provided a datetime object, rather than just passing it through as-is ๐คท
One day my long-standing PR to fix |expand and friends will be merged and I'll be more likely to "fix" more template issues like that
(or not)
This was it: {{ state_attr('script.lights_off', 'last_triggered') | as_local + (timedelta(minutes=3) + timedelta(minutes=7)) }} Thanks a lot @inner mesa & @mighty ledge !
The funny thing with those is that it's not recognized as datetime in devtools, but then it errors in the actual script/automation
No, I'm wrong here
It also fails in devtools
you technically can't have a datetime object as an attribute because it's not serializable
or "aren't allowed to"
you can
Can anyone tell me wat I do wrong? First I had created groups in Home Assistant (they give me the correct light count). Now I have deleted those and uses the groups of the Hue lights
{% set lightcount = expand('light.woonkamer') | selectattr( 'state', 'eq', 'on') | list | count %}
{{ lightcount }}
this gives me 1 light but there are 8 lights in the Hue group light.woonkamer
hue groups also don't have entities attached to them so expand won't work
i.e. you'll still need your HA groups
oh serious ๐ ... I just deleted all my groups in HA
you should check out the docs before making a switch like that ๐
But when I check the state of light.woonkamer in the developer tools I get all the entities printed of that Hue group
so the system knows which entity belong to that Hue group
lights:
- Voorraam woonkamer kleine raam
- Voorraam woonkamer grote raam
- Achterraam woonkamer deur
- Achterraam woonkamer muur
- Openhaard muur
- Servieskast strip
- Openhaard deur
- Tv ledstrip
right, tha'ts not entity_ids
that are exactle all the 8 lights in the group
and that attribute is named lights
yes
ok, then expand won't work
expand only expands the entity_id attribute and it needs to have valid entity_ids
which that is not
okay. So I have to create all groups in Home Assitant. Then the Hue group (which is default disabled) you have to use to have a better experience on setting all the lights on/off at one? Am i right?
okay
What is your aim?
my aim is that I have some sensor that count how many lights are on in a specific group. That was working perfect with the HA groups but now with the Hue groups Iit don't work ant more. But petro explained that that kind of information is not avilable from the hue group
So I will go recreate them, so that I can use the HA groups for counting lights and the Hue Groups to enable/disable the group (for a better experience what I have read)
If those lights are available in the Hue group in a separate attribute, couldn't you just grab that attr using state_attr and then use expand on the array from that?
it lists friendly hue light names
Ah, not the entity ids
yep, so it could be done only if the hue entities had a 'hue_friendly_name' attribute or something like that
a hue light has this attribute:
friendly_name: Openhaard deur
that's the home assistant friendly name
it needs to be the name that comes from hue
nope that don't exists
if you don't alter the names that come from hue, then you could potentially do it
okay but I think I'm going to restore my HA light groups (I have all text in my notepad) Then it will work again
and I don't know what would happen if you changed the name in hue
thanks for the help!
np
Hi!
How would one build a sensor that tells if a states value is at a "low point" given X amount of time? Example: Trigger automation when fuel price sensor is at 7-day-low.. Any ideas?
Thanks!
Could create a https://www.home-assistant.io/integrations/statistics with a state_characteristic: value_min and max_age of 7 days. Then have a template sensor that determine if the current value is equal to it (or just trigger directly on it).
If you trigger directly on it though, you'll need to figure out what you want to do if the value continues to decrease though.... otherwise, you'll see repeating triggers every time it updates. Whereas if you base it on the template sensor, you could trigger once the first time it is equal and not continue to trigger until it rises again.
I am very new to Home assistant. Just created a new sensors.yaml and pointed at in the configurations.
Treid to use code provided on home assistant page for 3em integrations. But i get "missing property platform" and "propterty utility meter not allowed" Where do i start ๐ Hope by posting on correct supprt channel in discord lol
Share what you have so far and what you're looking to get set up.
Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.
Shelly 3EM trying to make the code from this page work:
https://community.home-assistant.io/t/shelly-3em-3-phase-net-metering-templates-for-import-export-and-consumption/390237/164
Dont know if it is vice to post the entire code here ๐ Thank you for your help so far ๐
Click the link from the message, paste it in a code sharing site
and share the link
oh thats clever - https://dpaste.org/6wKY5
That section is technically a snip directly from a configuration.yaml
If you included a new sensor.yaml file and pasted it all in there, it wouldn't work
Only the section prior to utility_meter is for sensor
Was all of that pasted in sensors.yaml?
Yes.
How is your configuration.yaml referencing the sensors.yaml file? sensor: !include sensors.yaml? Or something different
like this| sensor: !include sensors.yaml
https://dpaste.org/z6VKB this should be the content of your sensors.yaml file then
The utility_meter stuff needs to either be put in the configuration.yaml directly, or split out similar to how you did it w/ sensors
Thank you. I have pasted this in sensors.yaml and have update the utility stuff in Chonfigurations.yaml.
In config yaml there is no error.
However in the sensors.yaml i have 9 errors most of them are stating: end of the stream or adocument seperator is expected. And one is line 38 power_consumptions Missing property "platform"
Oh what have i started at ๐
Try this in sensors.yaml, there were some garbage characters in there: https://dpaste.org/pHTOw
Wired that the code itself is doing this as it is posted to so many. I think you got 3 out of 9 issues. As it is know only showing 6 issues.
For this i think it may be easy to show in a picture
You can upload to imgur or another sharing site
INdeed it was probably dpast. TIL alot ๐ Dpast can show raw and use taht for future things haha
Thank you so much for your help and time.
I dont want to fiddel with it know that it works. However, i am curious to how easy it would be to copy the original code directly to configurations.yaml. I treid that in the start aswell with some errors. Does not seem on the forum that any others are having the issue ๐
If you just pasted that snippet as into into configuration.yaml, it should've worked. However, as you use HA more and more, you would've done what you did here by splitting the configuration
It makes it much easier in the long term to manage things
Oh i got it working know, tried both had to learn lol. Nice to know i am on the right track.
Again thank you very much for your help ๐
Awesome, glad to hear, you're welcome
is there a better way to do this:
{% if bed 'unavailable' or 'off' or 'unknown' %}
Out
{% elif bed 'off' %}
Out
{% else %}
In
{% endif %}```
Well, your elif will never be true
{{ is_state('binary_sensor.withings_in_bed_sensor', 'on') | iif("In", "Out") }}
This will be equivalent ๐
https://www.home-assistant.io/docs/configuration/templating/#immediate-if-iif for further reading ๐
oh of course - thank you!
You were missing ==
bed == 'off', not just bed 'off'
But the solution of Rosemary is a lot better
Good Day All, I had this tamplate that monitored how long my power was off but is no longer working.
example:
- platform: history_stats
entity_id: sensor.grid_frequency
name: no_mains
state: 0
type: time
start: "{{ now().replace(hour=0, minute=0, second=0) }}"
end: "{{ now() }}"
Any advise